我注意到在某些版本的Go语言中,第一个和第二个int变量之间的差距有时会增加。
package main
import (
"fmt"
"unsafe"
)
func main() {
a := 7
b := 8
c := 9
d := 10
fmt.Printf("a's address is %v\n", &a)
fmt.Printf("b's address is %v\n", &b)
fmt.Printf("c's address is %v\n", &c)
fmt.Printf("d's address is %v\n", &d)
baSpan := uintptr(unsafe.Pointer(&b)) - uintptr(unsafe.Pointer(&a))
cbSpan := uintptr(unsafe.Pointer(&c)) - uintptr(unsafe.Pointer(&b))
dcSpan := uintptr(unsafe.Pointer(&d)) - uintptr(unsafe.Pointer(&c))
// Go playground, Go 1.20 - Prints 8.
// Go playground, Go dev branch - Sometimes prints 8, sometimes 24.
// My machine, go1.20.4 windows/amd64 - Always prints 24.
fmt.Printf("b-a span is %v\n", baSpan)
fmt.Printf("c-b span is %v\n", cbSpan) // Prints 8
fmt.Printf("d-c span is %v\n", dcSpan) // Prints 8
}
去操场,去1.20-https://go.dev/play/p/BJIVC1cQQoT
Go playground,Go dev - https://go.dev/play/p/BJIVC1cQQoT?v=gotip
这些问题是:
1.为什么打印24?剩下的16个字节是什么?* (考虑到a
在64位机器上占用8个字节)*
1.为什么在围棋场上是随机的?
1.我们怎么知道其他16个字节是什么?我想这可以通过检查汇编代码来完成。还有其他办法吗?
1条答案
按热度按时间5fjcxozz1#
堆分配依赖于实现和运行时。
x.go
:https://go.dev/play/p/HeAMYeBG1_o?v=go1.20
https://go.dev/play/p/HeAMYeBG1_o?v=gotip