pointers - 为指针类型的字段赋值的简写是什么

标签 pointers go structure

<分区>

我成功了:

package main

import "fmt"

type test struct {
    A *int
    B string
}

func main() {
    x := 1
    var A test
    A.B = "hello"
    A.A = &x
    fmt.Printf("%s, %v", A.B, *A.A)
}

Playground :https://play.golang.org/p/iMsFBTWkRJU

我知道使用 x:=1A.A = &x 已经结束了。如何修改并使其更简单?

谢谢你的时间

最佳答案

例如,

package main

import "fmt"

type T struct {
    A *int
    B string
}

func newT(a int, b string) *T {
    return &T{A: &a, B: b}
}

func main() {
    t := newT(1, "Hello")
    fmt.Printf("%s, %v", t.B, *t.A)
}

输出:

Hello, 1

关于pointers - 为指针类型的字段赋值的简写是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49497832/

相关文章:

gwt - 使用 Maven 将 GWT 源代码整合到 WAR 中的最佳实践

javascript - 带有自定义 json 数据的 JsTree

pointers - 交换和元组分配的基本查询

c++ - 带有 if 语句的指针(地址)

go - 如何在 Go 中使用用户输入的 URL?

dictionary - 如何在 Go 中获取变量的内存大小?

c - 内存指针

c++ - 使用 `memcpy()` 为指针分配地址

regex - 带有非拉丁字符的 Golang 正则表达式

C++ 摆脱单例 : alternative to functors and static methods