gpt4 book ai didi

go - 在 Go 中直接在堆上构造原始类型?

转载 作者:IT王子 更新时间:2023-10-29 01:07:57 27 4
gpt4 key购买 nike

如何在 Go 中直接在堆上构造原始整数类型?

对于复合文字,following syntax支持:

return &File{fd, name, nil, 0}

但是 int 和 friends 似乎不存在这样的等价物:

Size: &uint64(entry.FileInfo.Size()),

d:\gopath\src\bitbucket.org\anacrolix\dms\dlna\dms\dms.go:271: cannot take the address of uint64(entry.FileInfo.Size())

最佳答案

Address operators

For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a composite literal.

原始整数类型不可寻址。如果整数是寄存器变量,则没有内存地址。如果整数是常量,提供其内存地址将允许修改它。

因此,创建一个整型变量并取其地址或使用整型指针类型。例如,

package main

import "fmt"

func main() {
var i int = 42
var pi = &i
j := int(7)
pj := &j
var pk = new(int)
k := *pk
fmt.Println(i, pi)
fmt.Println(j, pj)
fmt.Println(k, pk)
}

输出:

42 0xf840043100
7 0xf840043108
0 0xf840043110

关于go - 在 Go 中直接在堆上构造原始类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12881175/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com