英文:
Golang - Cannot take address of variable in struct error, untyped string constant
问题
我有一个存储指针的结构体,如下所示:
type Req struct {
Name *string
Address *string
Number string
}
我试图创建一个具有这个结构体类型的变量,并按以下方式赋值:
req := Req{
Name: &"Alice",
Address: &"ABCDEF",
Number: "123456",
}
当我这样做时,我会得到以下错误:
invalid operation: cannot take address of "Alice" (untyped string constant)
invalid operation: cannot take address of "ABCDEF" (untyped string constant)
我不太清楚为什么会出现这个错误,以及为什么 "Alice" 和 "ABCDEF" 是无类型的字符串常量。我知道我可以将这些值分配给新变量,并在我使用的 req
结构体中使用这些变量的指针。但我想知道为什么我的当前方法是错误的。我该如何使其工作?
英文:
I have a struct which stores pointers like this
type Req struct {
Name *string
Address *string
Number string
}
I'm trying to create a variable with this struct type and assign values as follows
req := Req{
Name = &"Alice"
Address = &"ABCDEF"
Number = "123456"}
When I do this, I get the following error
invalid operation: cannot take address of "Alice" (untyped string constant)
invalid operation: cannot take address of "ABCDEF" (untyped string constant)
I'm not really clear on why this error is coming up and why "Alice" and "ABCDEF" are untyped string constants. I know I can assign the values to new vars and use the vars pointers in the req
struct I'm using. But I'm trying to understand why my current approach is wrong. How can I make it work?
答案1
得分: 1
变量有地址。未类型化的常量只是值,它们没有地址。您可以获取使用未类型化常量初始化的变量的地址:
v := "Alice"
Name := &v
或者,定义一个方便的函数:
adr := func(s string) *string {return &s}
req := Req{
Name: adr("Alice"),
Address: adr("ABCDEF"),
Number: "123456",
}
英文:
Variables have addresses. Untyped constants are simply values, and they do not have addresses. You can get the address of a variable that is initialized using the untyped constant:
v:="Alice"
Name=&v
or, define a convenience function:
adr:=func(s string) *string {return &s}
req := Req{
Name: adr("Alice"),
Address: adr("ABCDEF"),
Number: "123456",
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论