You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
go doc fmt
go run filename.go // go run . - if you have multiple Go source files in the same directory
go build filename.go
go install package_name // Compiles and installs a Go package or program. It places the binary in the $GOPATH/bin directory.
go get github.com/user/package_name // Used to download and install Go packages from remote repositories
go tidy // After running this command, your go.mod file will be updated to remove unused dependencies and potentially update version ranges to specific versions.
go test // Used to run tests in your Go code. It automatically searches for files with names matching the pattern _test.go and executes test functions.
go fmt filename.go
go vet filename.go // It is a static analysis tool that checks your code for suspicious constructs or potential issues.
go tool dist list // shows supported combination for "go build"
Define variable
s := "" // practically use
var s string // practically use
var s = ""
var s string = ""
name := "John"
var age int = 30
value := 1000.476
a := true
fmt.Printf("My name is %s.\nMy age is %d.\nI have %f$.\n%t", name, age, value, a)
Logical operators
a := 3
b := 10
if a > 1 && b > 9 {
fmt.Println("Right!")
}
if a > 2 || b > 9 {
fmt.Println("Right!")
}
if a != 2 {
fmt.Println("Right!")
}
Loops
for i := 1; i <= 5; i++ {
fmt.Printf("Hello %d\n", i)
}
∞
for {
fmt.Printf("Loop")
}
more loop's options
for i := 1; i <= 5; i++ {
if i%2 != 0 {
continue
}
fmt.Println(i)
}
for i := 1; i <= 5; i++ {
if i%2 != 0 {
break
}
fmt.Println(i)
}
while loop
i := 0
for i < 5 {
fmt.Println(i)
i++
}
nums := []int{1, 2, 3, 4, 5}
for i := 0; i < len(nums); i++ {
fmt.Println(nums[i])
}
Switches
name := "John"
switch name {
case "Jordan":
fmt.Println("Wrong")
case "Kate":
fmt.Println("Wrong")
case "John":
fmt.Println("Hello John!")
default:
fmt.Println("Something else wrong!")
}
Switch's fallthrough
number := 10
switch {
case number > 1:
fmt.Println("Number is greater than 1")
fallthrough
case number > 11:
fmt.Println("Number < 11")
}
func sum(a int, b int) int {
result := a + b
return result
}
func main() {
value := sum(5, 9)
fmt.Println(value)
}
func math_func(a int, b int) (int, int, int, int) {
sum := a + b
sub := a - b
mul := a * b
div := a / b
return sum, sub, mul, div
}
func main() {
sum, sub, mul, div := math_func(3, 5)
fmt.Println(sum, sub, mul, div)
}
// Better return format
func math_func(a int, b int) (sum int, sub int, mul int, div int) {
sum = a + b
sub = a - b
mul = a * b
div = a / b
return
}
func main() {
sum, sub, mul, div := math_func(3, 5)
fmt.Println(sum, sub, mul, div)
}
func main() {
a := func(x string, y string) string {
return x + y
}
result := a("Hi ", "there!")
fmt.Println(result)
}