New to arrays, variadic functions and pointers

Hello there,

I am new to go and currently I am at the point where I just learned that hard-copy values are evil (in some cases). Now I have a small example here and want to to know:

  1. Why do I have to * (dereference) at the marked position in code

  2. Is this efficient what I am trying to achieve there or is there a better option to achieve the same result (with less memory consumption)?

    type SomeObject struct {
        a string
        b string
        c string
    }
    
    type SomeInterface interface {
        setup(name string, unknownAmountOfObjects ...*SomeObject)
    }
    
    type InterfaceTest struct {
        ExaxtAmountOfObjects *[3]SomeObject
        name string
    }
    
    // implement the interface by implementing this method
    func (interfacetest *InterfaceTest) setup(name string, somename ...*SomeObject) {
        interfacetest.name = name
        
        for i, value := range rotors {
            // check for size first
            if i < len(interfacetest.ExaxtAmountOfObjects) {
                // !!!! Why do I need to dereference here??!
                interfacetest.ExaxtAmountOfObjects[i] = *value
            }
        }
    }
    
    

Thanks for your help and suggestions in advance

Stefan

  1. Why do I have to * (dereference) at the marked position in code

ExaxtAmountOfObjects *[3]SomeObject holds a value of SomeObject but you are passing to function pointer(*SomeObject) to the object, that is why you need to dereference it.

Is this efficient what I am trying to achieve there or is there a better option to achieve the same result (with less memory consumption)?

ExaxtAmountOfObjects is an array which means it is a fixed size. setup is a variadic function, you can pass as much as you want. if I would see your function without it’s implementation I would pass 4 items to the function and expect all the elements in the array.

1 Like

This line

iterates of rotors which is not mentioned anywhere else in this code snippet. So we have no idea what valueis. It is not releated to somename in the signautre of SomeInterface.setup(...) . What is rotors?

3 Likes

1.) @kync Thanks, I somewhat mistaken variadic types with some sort of array. But you are right it is not :wink: Thanks

2.) @lutzhorn rotors is a typo… Of course it should mean SomeObject there

My mistake was also that there is a difference between:

*[3]Object

and

[3]*Object