Golang – 无法获取结构体中变量的地址错误,未指定类型的字符串常量

huangapple go评论85阅读模式
英文:

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>



huangapple
  • 本文由 发表于 2023年5月13日 01:13:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76238601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定