mirror of
https://gitee.com/shikong-sk/golang-study
synced 2025-04-18 17:28:06 +08:00
docs: 运算符 基础
This commit is contained in:
parent
3cf7dd1550
commit
88e4c72f85
@ -41,4 +41,20 @@ func main() {
|
||||
fmt.Println("a>=b :", a >= b)
|
||||
fmt.Println("a<b :", a < b)
|
||||
fmt.Println("a<=b :", a <= b)
|
||||
|
||||
fmt.Println("=========================================================")
|
||||
|
||||
// 位运算
|
||||
// 5 & 2 = 0101 & 0010 => 0000
|
||||
fmt.Printf("%d & %d => %d\n", 5, 2, 5&2)
|
||||
// 5 | 2 = 0101 | 0010 => 0111
|
||||
fmt.Printf("%d | %d => %d\n", 5, 2, 5|2)
|
||||
// 5 ^ 2 = 0101 ^ 0010 => 0111
|
||||
fmt.Printf("%d ^ %d => %d\n", 5, 2, 5^2)
|
||||
// 左移 1 << 3 = 1 * 2^3 = 8
|
||||
// 0001 => 1000
|
||||
fmt.Printf("%d << %d => %d\n", 1, 3, 1<<3)
|
||||
// 右移 8 >> 3 = 8 / 2^3 = 1
|
||||
// 1000 => 0001
|
||||
fmt.Printf("%d >> %d => %d\n", 8, 3, 8>>3)
|
||||
}
|
||||
|
@ -876,29 +876,29 @@ import (
|
||||
|
||||
// 1.假设这是个第三方包
|
||||
func f1(f func()) {
|
||||
fmt.Printf("# This is f1 func , Param is f func() : %T \n", f)
|
||||
f() // 调用传入的函数
|
||||
fmt.Printf("# This is f1 func , Param is f func() : %T \n", f)
|
||||
f() // 调用传入的函数
|
||||
}
|
||||
|
||||
// 2.自己实现的函数
|
||||
func f2(x, y int) {
|
||||
fmt.Printf("# This is f2 func , Param is x,y: %v %v\n", x, y)
|
||||
fmt.Printf("x ^ y = %v \n", math.Pow(float64(x), float64(y)))
|
||||
fmt.Printf("# This is f2 func , Param is x,y: %v %v\n", x, y)
|
||||
fmt.Printf("x ^ y = %v \n", math.Pow(float64(x), float64(y)))
|
||||
}
|
||||
|
||||
// 要求 f1(f2) 可以执行,此时由于f1 中的传递的函数参数并无参数,所以默认调用执行一定会报错。
|
||||
// 此时我们需要一个中间商利用闭包和匿名函数来实现,返回一个不带参数的函数。
|
||||
|
||||
func f3(f func(int, int), x, y int) func() {
|
||||
tmp := func() {
|
||||
f(x, y) // 此处实际为了执行f2函数
|
||||
}
|
||||
return tmp // 返回一个不带参数的函数,为返回给f1函数
|
||||
tmp := func() {
|
||||
f(x, y) // 此处实际为了执行f2函数
|
||||
}
|
||||
return tmp // 返回一个不带参数的函数,为返回给f1函数
|
||||
}
|
||||
|
||||
func main() {
|
||||
ret := f3(f2, 2, 10) // 此时函数并为执行只是将匿名函数进行返回。先执行 f3(fun,x,y int)
|
||||
f1(ret) // 当传入f1中时ret()函数便会进行执行。再执行 f1() ,最后执行 f2(x,y int)
|
||||
ret := f3(f2, 2, 10) // 此时函数并为执行只是将匿名函数进行返回。先执行 f3(fun,x,y int)
|
||||
f1(ret) // 当传入f1中时ret()函数便会进行执行。再执行 f1() ,最后执行 f2(x,y int)
|
||||
}
|
||||
```
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user