Fundamentals in Go
Identifiers
In programming, identifiers are used for naming purposes. Essentially, identifiers are user-defined names for program components. In the Go language, identifiers can represent variable names, function names, constants, statement labels, package names, or types.
Example:
package main
import "fmt"
func main() {
var course = "Learn Go Programming"
}
In the example above, there are three identifiers:
main
: The name of the package.main
: The name of the function.course
: The name of the variable.
Rules for Defining Identifiers:
To define valid Go identifiers, certain rules must be followed. Failing to adhere to these rules results in compile-time errors:
- The identifier name must start with a letter or an underscore (
_
). It may include letters (a-z
,A-Z
), digits (0-9
), and underscores (_
). - The identifier name cannot start with a digit.
- Identifiers are case-sensitive.
- Reserved keywords cannot be used as identifier names.
- While there is no maximum limit on identifier length, it is recommended to keep names between 4 and 15 characters for readability.
Example:
// Valid identifiers:
_student23
course
course2023
CourseName
COURSE_NAME
// Invalid identifiers:
123course
func
package
Predeclared Constants:true
, false
, iota
, nil
Predeclared Types:int
, int8
, int16
, int32
, int64
, uint
, uint8
, uint16
, uint32
, uint64
, uintptr
, float32
, float64
, complex128
, complex64
, bool
, byte
, rune
, string
, error
Predeclared Functions:make
, len
, cap
, new
, append
, copy
, close
, delete
, complex
, real
, imag
, panic
, recover
Blank Identifier (_): The underscore character
_
is a special identifier used as an anonymous placeholder in declarations, assignments, or operands.Exported Identifiers: An identifier is considered exported if it starts with an uppercase letter and is declared in the package block or as a variable, function, type, or method name within a package. These identifiers can be accessed outside the package.
Example of Exported Identifiers:
File: utilities.go
// utilities.go
package utilities
// Exported variable
var GreetingMessage = "Welcome to Go Utilities!"
File: main.go
// main.go
package main
import (
"fmt"
"path/to/yourproject/utilities"
)
// Exported variable
var ApplicationName = "Go Identifier Tutorial"
func main() {
// Accessing exported identifier within the same file
fmt.Println(ApplicationName)
// Accessing exported identifier from another package
fmt.Println(utilities.GreetingMessage)
}
Output:
Go Identifier Tutorial
Welcome to Go Utilities!
Keywords or Reserved words are the words in a programming language that serve specific purposes or represent predefined functionalities. These words are restricted from being used as identifiers, such as variable names or function names. Using these reserved words as identifiers will lead to compile-time errors.
Example:
// Go program to demonstrate the use of keywords
package main
import "fmt"
// Here, package, import, func, var are keywords
func main() {
// Using a valid identifier
var message = "Hello, Go Language!"
fmt.Println(message)
// Attempting to use a reserved word as an identifier
// will result in a compile-time error
// var return = "Invalid Identifier"
}
Output:
Hello, Go Language!
Go language contains 25 keywords in total, as listed below:
break case chan const continue
default defer else fallthrough for
func go goto if import
interface map package range return
select struct switch type var
Example:
// Go program demonstrating the usage of keywords
// The package keyword is used to specify the main package
package main
// The import keyword is used to include the "fmt" package
import "fmt"
// The func keyword is used to define a function
func main() {
// The var keyword is used to declare variables
// These are valid identifiers: name, lang, and topic
var name = "Learn Go Programming"
var lang = "Go Language"
var topic = "Keywords"
fmt.Printf("Learning Platform: %s", name)
fmt.Printf("\nProgramming Language: %s", lang)
fmt.Printf("\nTopic: %s", topic)
}
Output:
Learning Platform: Learn Go Programming
Programming Language: Go Language
Topic: Keywords
Data Types in Go
Data types in Go define the kind of data a variable can store. Go provides several categories of data types, which are:
- Basic Type: Includes numbers, strings, and booleans.
- Aggregate Type: Includes arrays and structs.
- Reference Type: Includes pointers, slices, maps, functions, and channels.
- Interface Type: Defines a method set.
Here, we’ll delve into the Basic Data Types, further divided into:
- Numbers
- Booleans
- Strings
Numbers
In Go, numbers are categorized into:
Integers: Go supports both signed and unsigned integers in various sizes:
Data Type | Description |
---|---|
int8 | 8-bit signed integer |
int16 | 16-bit signed integer |
int32 | 32-bit signed integer |
int64 | 64-bit signed integer |
uint8 | 8-bit unsigned integer |
uint16 | 16-bit unsigned integer |
uint32 | 32-bit unsigned integer |
uint64 | 64-bit unsigned integer |
int | Same size as the machine’s word size |
uint | Same size as the machine’s word size |
rune | Alias for int32 representing Unicode |
byte | Alias for uint8 |
uintptr | Holds pointer-sized unsigned integers |
Arithmetic operations like addition, subtraction, multiplication, division, and modulus are supported.
Example:
// Go program to demonstrate integers
package main
import "fmt"
func main() {
// Example with unsigned 8-bit integer
var num1 uint8 = 200
fmt.Println(num1, num1-50)
// Example with signed 16-bit integer
var num2 int16 = 10000
fmt.Println(num2+500, num2-500)
}
Output:
200 150
10500 9500
Floating-Point Numbers
Go provides two types of floating-point numbers:
Data Type | Description |
---|---|
float32 | 32-bit IEEE 754 floating-point number |
float64 | 64-bit IEEE 754 floating-point number |
Arithmetic operations like addition, subtraction, multiplication, and division are supported.
Example:
// Go program to illustrate floating-point numbers
package main
import "fmt"
func main() {
num1 := 18.75
num2 := 41.35
// Perform subtraction
result := num2 - num1
// Display result and type
fmt.Printf("Result: %f\n", result)
fmt.Printf("Type of result: %T\n", result)
}
Output:
Result: 22.600000
Type of result: float64
Booleans: The boolean type represents one of two values: true
or false
. Boolean values are not implicitly or explicitly converted to other types.
Example:
// Go program to demonstrate booleans
package main
import "fmt"
func main() {
var flag1 = (5 > 3) // true
var flag2 = (5 < 3) // false
fmt.Println("Flag1:", flag1)
fmt.Println("Flag2:", flag2)
fmt.Printf("Type of flag1: %T\n", flag1)
}
Output:
Flag1: true
Flag2: false
Type of flag1: bool
Strings
Strings in Go are immutable sequences of bytes. They support concatenation using the +
operator.
Example:
// Go program to demonstrate strings
package main
import "fmt"
func main() {
// Define a string
text := "Go Programming"
// Print string length and value
fmt.Printf("Length: %d\n", len(text))
fmt.Printf("String: %s\n", text)
}
Output:
Length: 14
String: Go Programming
String Concatenation
Example:
// Go program for string concatenation
package main
import "fmt"
func main() {
str1 := "Hello, "
str2 := "World!"
// Concatenate strings
result := str1 + str2
fmt.Println("Concatenated String:", result)
}
Output:
Concatenated String: Hello, World!
Constants- Go Language
As the name CONSTANTS suggests, it means fixed or unchanging. Similarly, in programming, constants are values that, once defined, cannot be modified. Constants in Go can have various data types like integers, floating-point numbers, characters, or string literals.
How to Declare Constants
Constants are declared similarly to variables, but the const
keyword is used as a prefix. Unlike variables, constants cannot be declared using the shorthand :=
syntax.
Example:
package main
import "fmt"
const Gravity = 9.8
func main() {
const Platform = "GoLang Basics"
fmt.Println("Welcome to", Platform)
fmt.Println("Gravity on Earth is", Gravity)
const IsLearningFun = true
fmt.Println("Is learning Go fun?", IsLearningFun)
}
Output:
Welcome to GoLang Basics
Gravity on Earth is 9.8
Is learning Go fun? true
Typed and Untyped Numeric Constants
- Typed Constants behave like immutable variables and can interact only with values of the same type.
- Untyped Constants behave like literals and can interact with similar types.
Constants can be defined either with or without a type.
Example:
const untypedInt = 200
const untypedFloat = 45.6
const typedInt int = 200
const typedFloat float64 = 45.6
Types of Constants in Go
- Numeric Constants
- String Literals
- Boolean Constants
1. Numeric Constants:
Numeric constants are precise values. Since Go is a statically typed language, it does not allow mixing numeric types in operations. For instance, adding an int
to a float64
is not allowed.
Integer Constants: Integer constants can be written in:
- Decimal (base 10)
- Octal (base 8, prefixed with
0
) - Hexadecimal (base 16, prefixed with
0x
or0X
)
Example:
package main
import "fmt"
func main() {
const comp = complex(5, 7) // 5 is real, 7 is imaginary
fmt.Println("Complex Number:", comp)
fmt.Println("Real Part:", real(comp))
fmt.Println("Imaginary Part:", imag(comp))
}
Complex Constants: A complex constant consists of a real and an imaginary part, separated by a comma and enclosed within parentheses.
Example:
package main
import "fmt"
func main() {
const comp = complex(5, 7) // 5 is real, 7 is imaginary
fmt.Println("Complex Number:", comp)
fmt.Println("Real Part:", real(comp))
fmt.Println("Imaginary Part:", imag(comp))
}
Output:
Value of Pi: 3.14159
Scientific Notation: 123
2. String Literals
Go provides two types of string literals:
- Double quotes (
" "
): For plain strings with escape sequences. - Backticks (
` `
): For raw string literals.
Example:
package main
import "fmt"
func main() {
const greeting = "Hello, Go!"
const rawString = `Line 1
Line 2
Line 3`
fmt.Println(greeting)
fmt.Println(rawString)
}
Output:
Hello, Go!
Line 1
Line 2
Line 3
3. Boolean Constants
Boolean constants represent true
and false
.
Example:
package main
import "fmt"
const IsEnabled = true
func main() {
type status bool
var defaultStatus = IsEnabled
var customStatus status = IsEnabled
fmt.Println("Default Status:", defaultStatus)
fmt.Println("Custom Status:", customStatus)
}
Output:
Default Status: true
Custom Status: true
Defining Multiple Constants
You can declare multiple constants in a single block using parentheses.
Example:
package main
import "fmt"
const (
Language = "Go Programming"
Version = 1.19
Open = true
)
func main() {
fmt.Println("Language:", Language)
fmt.Println("Version:", Version)
fmt.Println("Open Source:", Open)
}
Output:
Language: Go Programming
Version: 1.19
Open Source: true
Related Chapters
- Introduction of Go-Lang
- Fundamentals in Go
- Control Statement in Go
- Functions & Methods in Go
- Structures in Go
- Arrays in Go
- Slices in Go
- File Handling in I/O
- Pointers in Go
- Concurrency in Go
- Object Oriented Programming in Go
- Defer and Error Handling in Go
- First Class Functions in Go
- Reflection in Go
- File Handling in Go