Go language type system syntax-basics
Go Language Type System Syntax Basics
Variable Declaration and Assignment
In Go, variables are declared using the var keyword followed by the variable name and type. The := operator allows for concise assignment, especially for simple variables.
var x int = 42
var y string = "hello"
var z bool = true
The := operator enables implicit type inference, reducing the need to explicitly specify the type.
var a int32 := 100
var b rune := 'A'
Type Declarations and Variables
Go requires explicit type declarations for variables, ensuring clarity and preventing type mismatches. Types include built-in types like int, string, bool, and user-defined types.
var c int64 = 1_000_000
var d float32 = 3.14
var e interface{} = "text"
Type declarations are critical for maintaining code reliability, as Go's type system enforces strict rules.
Literals and Constants
Go supports various literals, including numeric values, strings, and booleans. Numbers can be written in decimal, octal, or hexadecimal formats.
var f int8 = 0xFF
var g int16 = 0x1000
var h int32 = 1000000
Strings are enclosed in double quotes, and booleans use true or false.
var i string = "Go is simple"
var j bool = true
Operators and Expressions
Go uses a variety of operators for arithmetic, comparison, and logical operations.
- Arithmetic:
+,-,*,/ - Comparison:
==,!=,>,<,>=,<= - Assignment:
=,:= - Logical:
&&,||,!
var k int = 5 + 3
var l int = 10 > 5
var m int = 2 && 1
The := operator simplifies assignment, particularly for single-value expressions.
Type Assertions and Interface{}
Go allows type assertions to extract values from interfaces, enabling dynamic typing.
var n interface{} = 42
var p int = n.(int)
Type assertions are useful when working with objects that implement multiple interfaces, ensuring type safety at runtime.
Type Conversions and Casting
Go supports explicit type conversions using int(), string(), or float() functions.
var q int = 100
var r int32 = int32(q)
var s float32 = float32(q)
Casting is done with int(), string(), or float() functions, ensuring compatibility between types.
Conclusion
Go's type system emphasizes clarity and safety through explicit declarations, literals, and operators. Understanding syntax fundamentals like variable assignment, type declarations, and operator usage is essential for writing correct and efficient Go code.