#Returning pointer to generic struct

33 messages · Page 1 of 1 (latest)

woven furnace
#

I've written this function but it returns nil instead of a valid pointer to the struct
Why is this happening?

 func NewBuffer[T any](length int) *Buffer[T] {
    return &Buffer[T]{
        data:   make([]T, length),
        length: 0,
        cap:    length,
        head:   0,
        tail:   0,
    }
}
timber niche
#

could you explain a bit more about how you came to the conclusion that it's returning nil?

woven furnace
#

I tried to call a function on it and it was nil

timber niche
#

what specifically was nil? it's hard to say with only that much information. there are other things that could have gone wrong, and at this point that's an unknown unknown

#

can you show a specific call where actually running NewBuffer(…) == nil evaluates to true?

woven furnace
#
t := NewBuffer[int](10)
t == nil
dusky shore
#

works fine

timber niche
#

not just assuming so

woven furnace
#

I am running it

timber niche
#

that code doesn't compile (and you sent it just a few seconds after i asked), so it doesn't seem like it to me

woven furnace
#

That's an example of how I am calling it
I know the second line wouldn't compile

timber niche
#

i'm not trying to be difficult, but it really seems like something else is going wrong. the premise of your original question—that NewBuffer returns nil—just isn't possible with what you're showing.

timber niche
#

if you can provide a more complete, runnable example that reproduces this that would be great.

dusky shore
#

at some point whatever you are checking is set to nil or never set to anything other than nil but using your constructor function, everything works as expected.

#

well, the second line might not compile because it does not make sense, as you are not doing anything with the bool value of that statement.

#

assign it to a variable and print it

woven furnace
#

I did

2023/07/29 04:00:57 t &{[0 0 0 0 0 0 0 0 0 0] 0 10 0 0}
2023/07/29 04:00:57 &{<nil> <nil> <nil> <nil> <nil> 0 0}
panic: runtime error: invalid memory address or nil pointer dereference

This doesn't happen on go playground
https://goplay.tools/snippet/GqDQtS07Do8

dusky shore
#

can you paste it into the go playground

#

I'm on my phone

#

and that website is awful on my phone :/

woven furnace
#

it only happens locally

dusky shore
#

looks fine. You might need to shere more code

#

share

woven furnace
#

Like honestly that's all I'm testing with

dusky shore
#

yan you post your exact complete code and the corresponding output

#

can

dusky shore
woven furnace
#

It works now