简单的方法来分配int指针值? [英] Easy way to assign int pointer values?

查看:77
本文介绍了简单的方法来分配int指针值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 struct ,看起来像

  type foo struct { 
i * int
}

如果我想设置 i 为1,我必须

  throwAway:= 1 
instance:= foo {i:& throwAway}

有没有办法在一行中做到这一点,而不必给我新的 i 赋值它自己的名字(在这种情况下 throwaway )?

解决方案

正如邮件列表,你可以这样做:

  func intPtr(int)* int {



















  instance:= foo {i:intPtr(1)} 

如果你必须经常这样做。 intPtr 获取内联(见 go build -gcflags'-m'输出),所以它应该接近没有性能罚款。


Given a struct that looks like

type foo struct {
 i *int
}

if I want to set i to 1, I must

throwAway := 1
instance := foo { i: &throwAway }

Is there any way to do this in a single line without having to give my new i value it's own name (in this case throwaway)?

解决方案

As pointed in the mailing list, you can just do this:

func intPtr(i int) *int {
    return &i
}

and then

instance := foo { i: intPtr(1) }

if you have to do it often. intPtr gets inlined (see go build -gcflags '-m' output), so it should have next to no performance penalty.

这篇关于简单的方法来分配int指针值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆