我希望将int切片作为构造函数的输入,并返回指向原始列表的指针,将其类型强制转换为我的外部定制类型(type IntList []int).

我可以这样做:

type IntList []int

func NewIntListPtr(ints []int) *IntList {
    x := IntList(ints)
    return &x
}

但我不能这么做:

type IntList []int

func NewIntListPtr(ints []int) *IntList {
    return &ints
}

// or this for that matter:

func NewIntListPtr(ints []int) *IntList {
    return &(IntList(ints))
}

// or this

func NewIntListPtr(ints []int) *IntList {
    return &IntList(*ints)
}

// or this

func NewIntListPtr(ints *[]int) *IntList {
    return &(IntList(*ints))
}

有没有一句俏皮话来实现这一点?

推荐答案

您可以这样做:

func NewIntListPtr(ints []int) *IntList {
    return (*IntList)(&ints)
}

Go相关问答推荐

区分Terminal和Hook Zerolog Go中的错误级别日志(log)输出

如何从google.golang.org/grpc/stats包中将golang中不同事件的输出进行组合,以获取func HandlePRC

链自定义GRPC客户端拦截器/DialOptions

在Mac中使用uname获取处理器体系 struct 时,在为AMD64构建Go二进制时出现错误结果

使用Go使用Gorm使用外键对数据进行排序

如何使用中间件更改http请求的响应代码?

从文件读取字节,将其保存到 struct 体并修改值

不接受来自 stdin 的重复输入

在 Go 中使用 Apache Arrow 按时间间隔对事件进行分区

Opensearch 错误 ping 弹性服务器:由未知权威签署的 x509 证书

我突然无法再将我的 GoLang 应用程序部署到 Google AppEngine

Go 中如何调用测试函数?

无法将 graphql-ws 连接到 gqlgen

将 big.Int 转换为 [2]int64,反之亦然和二进制补码

如何根据 Go 中第二次出现的分隔符拆分字符串?

Golang:隐式 struct 匹配

gorm 获取列名

Golang Echo Labstack 如何在模板视图中调用函数/方法

在 Golang 中使用 OR 条件验证 struct 的两个字段

HTTP 重定向不呈现新页面