Skip to main content

条件判断 Conditionals

if height > 4 {
fmt.Println("You are tall enough!")
}
if height > 6 {
fmt.Println("You are super tall!")
} else if height > 4 {
fmt.Println("You are tall enough!")
} else {
fmt.Prinln("You are not tall enough!")
}

Operators in Go

  • == equal to
  • != not equal to
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to

The initial statement of an if block

if INITIAL_STATEMENT; CONDITION {
}

应用前

length := getLength(email)
if length < 1 {
fmt.Prinln("Email is invalid")
}

应用后

if length := getLength(email); length < 1 {
fmt.Prinln("Email is invalid")
}

函数 Functions

func sub(x int, y int) int {
return x - y
}

func concat(s1 string, s2 string) string {
return s1 + s2
}

Multiple parameters

When multiple arguments are of the same type, the type only needs to be declared after the last one, assuming they are in order.

func add(x, y int) int {
return x + y
}

func createUser(firstName, lastName string, age int) {
fmt.Printf("My name is %s %s, I'm %d years old\n", firstName, lastName, age)
var returnOfSprintf string = fmt.Sprintf("My name is %s %s, I'm %d years old\n", firstName, lastName, age)
fmt.Println(returnOfSprintf)
}

声明语法 Declaration syntax

The style of language used to creat new varaible, types, functions, etc.

与传统的声明方式不同

x int
p *int
a [3]int

处理复杂的语法情况会比较方便阅读。

问题: Which language's declaration syntax reads like English from left-to-right?
答: Go
比如:

Go 可以把函数当作一个类型放入函数的输入变量中,比如下方的 func(int, int) int,这是一个 input parameter type, 一个输入变量声明。

f func(func(int, int) int, int), int

这段代码有英语表达是: A function named 'f' that takes a function and an int as arguments and return an int.

Memory & code

In Go, varaibles are passed by vallue not reference.

func wrongExample() {
x := 5
increment(x)

fmt.Println(x)
/*
stiull prints 5
because the increment function
received a copy of x
*/
}

func increment(x int) {
x++
}
func goodExample() {
x := 5
x = increment(x)

fmt.Println(x) // Correct answer as 6

}

func increment(x int) int {
x++
return x
}