GolangStudy/day4/assignment.go

58 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import "fmt"
func main() {
// 赋值有很多种办法
/*
x = 1 // 命名变量的赋值
*p = true // 通过指针间接赋值
person.name = "bob" // 结构体字段赋值
count[x] = count[x] * scale // 数组、slice或map的元素赋值
*/
// 可以使用 += -= *= 这种简短的赋值方法
var num1, num2 = 2, 3
// 效果等同 num2 = num2 + num1
num2 += num1
fmt.Println("num2: ", num2) // 5
// 元祖赋值
// 在var.go种我们使用的交换两个变量值就是元祖赋值
fmt.Println("num1, num2", num1, num2) // 2, 5
num1, num2 = num2, num1 // 交换
fmt.Println("num1, num2", num1, num2) // 5, 2
//或者是计算两个整数值的的最大公约数
gcd := func(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
//或者斐波那契数列
fib := func(n int) int {
x, y := 0, 1
for i := 0; i < n; i++ {
x, y = y, x+y
}
return x
}
fmt.Println("GCD:21, 14: ", gcd(21, 14))
fmt.Println("fib:10: ", fib(10))
// 赋值语句是显式的赋值形式,但是程序中还有很多地方会发生隐式的赋值行为:
// 函数调用会隐式地将调用参数的值赋值给函数的参数变量,
// 一个返回语句会隐式地将返回操作的值赋值给结果变量,
// 一个复合类型的字面量也会产生赋值行为。
medals := []string{"gold", "silver", "bronze"}
fmt.Println(medals)
// 隐式地对slice的每个元素进行赋值操作类似这样写的行为
medals[0] = "gold"
medals[1] = "silver"
medals[2] = "bronze"
fmt.Println(medals)
}