Basic Syntax
Variables and Types
var x int // variable declaration
var x = 42 // variable declaration with initialization
x := 42 // shorthand variable declaration with initialization
var x, y, z int // declare multiple variables
const x = 42 // declare a constant
var x = "hello" // variable of string type
var x = true // variable of boolean type
var x = 3.14 // variable of float64 type
var x = []int{1, 2} // variable of slice type
Functions
func name(arg1 type1, arg2 type2) return_type {
// function body
return value
}
func add(a, b int) int {
return a + b
}
Control Structures
if condition {
// code to be executed if condition is true
} else if condition2 {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
for i := 0; i < 10; i++ {
// code to be executed repeatedly
}
switch variable {
case value1:
// code to be executed if variable == value1
case value2:
// code to be executed if variable == value2
default:
// code to be executed if none of the cases match
}
Pointers
var x int = 10
var p *int = &x // pointer to x
fmt.Println(*p) // dereference pointer to get value of x
*p = 20 // change value of x via pointer
Packages
import "fmt" // import package named fmt
func main() {
fmt.Println("Hello, world!") // use function from fmt package
}
Arrays and Slices
Arrays
var a [5]int // declare an array of 5 integers
a[0] = 1 // set the first element of the array
b := [5]int{1, 2, 3, 4, 5} // declare and initialize an array
Slices
var s []int // declare a slice
s = append(s, 1) // add an element to the end of the slice
s = append(s, 2, 3, 4) // add multiple elements to the end of the slice
s = s[1:3] // slice the slice to get a new slice [2, 3]
Structs
type Person struct {
name string
age int
}
p := Person{name: "John", age: 30} // create a new Person
p.age = 31 // change the value of age
Interfaces
type Shape interface {
area() float64
}
type Circle struct {
x, y, r float64
}
func (c Circle) area() float64 {
return math.Pi * c.r * c.r
}
func getArea(s Shape) float64 {
return s.area()
}
c := Circle{x: 0, y: 0, r: 5}
fmt.Println(getArea(c)) // print the area of the Circle