Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to assign int pointer values?

Tags:

go

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)?

like image 293
MushinNoShin Avatar asked Apr 08 '15 16:04

MushinNoShin


2 Answers

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.

like image 55
Ainar-G Avatar answered Sep 17 '22 17:09

Ainar-G


No this is not possible to do in one line.

like image 38
Volker Avatar answered Sep 18 '22 17:09

Volker