How variables are defined and reused, and how literals are expressed.
Variables and Constants
Variables and Constants
none
go
Go Language
Defining a Variable
How to define a variable of a specific datatype.
Error Loading
Missing
Variables
func main() { var x int = 100 fmt.Println(x) }
Defining a Constant
How to define an immutable variable.
Missing
Constants
Go has true constants defined using const
:
const PI float64 = 3.1415 func main() { const count int = 10 // Constants cannot be modified var mutableCount int = 10 mutableCount += 1 // Allowed fmt.Println(PI, mutableCount) }
- Variables must have an explicit type or use
:=
for type inference.
Complex Literals
Native support for literal complex datatypes (non-primitive types).
Missing
Literals
Go supports various literals:
func main() { var myInt int = 10 var myBinary int = 0b1010 var myOctal int = 0o12 var myHex int = 0xA var myFloat float64 = 10.5 var mySciNot float64 = 2.0e3 var myBool bool = true var myByte byte = 'A' fmt.Println(myInt, myBinary, myOctal, myHex, myFloat, mySciNot, myBool, myByte) }
For strings, Go supports raw and multi-line strings:
func main() { myStr := "hello" myStrDouble := "hello" myMultiLine := `hello there` myRaw := `New\nLine` // Raw string, ignores escape sequences name := "Go" myFormatted := fmt.Sprintf("Hello %s", name) fmt.Println(myStr, myStrDouble, myMultiLine, myRaw, myFormatted) }
Complex types:
func main() { myArray := [3]int{1, 2, 3, 4, 5, 6} // [3]int (array with fixed length) slice := arr[1:4] // Slice referencing elements {2, 3, 4} emptySlice := []int{} // Empty slice addSlice = append(slice, 100) mySlice := []int{1, 2, 3} // []int (slice, dynamic array) myMap := map[string]int{"age": 30, "score": 100} // map[string]int (dictionary) mySet := map[int]struct{}{1: {}, 2: {}, 3: {}} // map[int]struct{} (set workaround) myBytes := []byte("hello") // []byte (byte slice) fmt.Printf("After append %d: len=%d cap=%d %v\n", i, len(slice), cap(slice), slice) copySlice := make([]int, len(original)) // Allocate new memory copy(copySlice, original) // Copy values }
You can create an immutable slice to prevent unexpected mutations on the underlying array by using a wrapper (this is a workaround)
// Read-only slice wrapper type ReadOnlySlice interface { Get(index int) int Length() int } // ImmutableSlice struct type ImmutableSlice struct { data []int } // Methods to enforce read-only access func (s ImmutableSlice) Get(index int) int { return s.data[index] } func (s ImmutableSlice) Length() int { return len(s.data) } func main() { original := []int{1, 2, 3, 4, 5} readOnly := ImmutableSlice{data: original} fmt.Println("Element at index 2:", readOnly.Get(2)) // Allowed // readOnly.data[2] = 100 // Compilation error if `data` is unexported }