英文:
How to use pointer type in struct initializer?
问题
我无法弄清楚当结构字段是一个数字类型的引用类型别名时如何初始化它:
package main
import (
"fmt"
"encoding/json"
)
type Nint64 *int64
type MyStruct struct {
Value Nint64
}
func main() {
data, _ := json.Marshal(&MyStruct{ Value : ?? 10 ?? })
fmt.Println(string(data))
}
英文:
I cannot figure out how to initialize structure field when it is a reference type alias of the one of the number types:
package main
import (
"fmt"
"encoding/json"
)
type Nint64 *int64
type MyStruct struct {
Value Nint64
}
func main() {
data, _ := json.Marshal(&MyStruct{ Value : ?? 10 ?? })
fmt.Println(string(data))
}
答案1
得分: 1
你可以在这里添加一个额外的步骤 playground:
func NewMyStruct(i int64) *MyStruct {
return &MyStruct{&i}
}
func main() {
i := int64(10)
data, _ := json.Marshal(&MyStruct{Value: Nint64(&i)})
fmt.Println(string(data))
//或者这样
data, _ = json.Marshal(NewMyStruct(20))
fmt.Println(string(data))
}
英文:
You can't, you will have to add an extra step <kbd>playground</kbd>:
func NewMyStruct(i int64) *MyStruct {
return &MyStruct{&i}
}
func main() {
i := int64(10)
data, _ := json.Marshal(&MyStruct{Value: Nint64(&i)})
fmt.Println(string(data))
//or this
data, _ = json.Marshal(NewMyStruct(20))
fmt.Println(string(data))
}
答案2
得分: 1
我不认为你想引用 int64 的地址...
package main
import (
"encoding/json"
"fmt"
)
type Nint64 int64
type MyStruct struct {
Value Nint64
}
func main() {
data, _ := json.Marshal(&MyStruct{Value: Nint64(10)})
fmt.Println(string(data))
}
http://play.golang.org/p/xafMLb_c73
英文:
I don't think you want to reference to the address of an int64 ...
package main
import (
"encoding/json"
"fmt"
)
type Nint64 int64
type MyStruct struct {
Value Nint64
}
func main() {
data, _ := json.Marshal(&MyStruct{Value: Nint64(10)})
fmt.Println(string(data))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论