Easy way to assign int pointer values? [duplicate]
Asked Answered
T

2

5

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

Theologue answered 8/4, 2015 at 16:48 Comment(1)
I recommend to check this extensive answer to a very similar question.Unbend
G
10

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.

Glomerule answered 8/4, 2015 at 16:57 Comment(5)
You can also do instance := foo{ i: new(int) }; foo.i = 1; if you don't want to write a separate function.Youth
That's not right @FUZxxl, you can't assign 1 as a type int to *int. You end up back in the same situation as the OP.Hirundine
Sorry, try instance := foo{i : new(int) }; *foo.i = 1;Youth
@Youth I get this: type ‘foo’ has no method ‘i’Martine
@Martine Please ask a new question for that if you can't solve it yourself.Youth
E
5

No this is not possible to do in one line.

Exigible answered 8/4, 2015 at 16:51 Comment(5)
Gross. Any thoughts as to why not? Is it just too difficult to implement to remove an occasionally noisy line?Theologue
@MushinNoShin: a pointer is the address of some thing, so you need that thing.Glanti
@maerics: that was already understood, this was asking if there's any convenient ways to automatically do the memory allocation in the background and keep the unnecessary noise out of my code. See the accepted answer.Theologue
Pointers to ints are not that common and pointers to literal ints are very uncommon, so why bother with syntactical sugar?Exigible
@Exigible you should take a look at aws-sdk-golang, they've got pointers to literal ints for days.Pennywise

© 2022 - 2024 — McMap. All rights reserved.