FAQ
Hello,

I have a struct type and slice of the struct type:

type Pair struct {
fst byte
snd byte
status byte
__align byte
}

type Pairs []Pair

Now, is it okay to write my methods of Pairs as non pointers? I do not want
any values to be copied, to me it looks like its fine and efficient because
it's a slice:

func (self Pairs) Match(other Pairs) float64 {

Thanks

xxx

--

Search Discussions

  • Steven Blenkinsop at Dec 1, 2012 at 9:53 pm
    Yes. Each time you call the method, only the 3 word slice value is copied,
    not the Pair array it references. However, because the slice value itself
    is a copy, you won't be able to effectively reassign it inside the method
    (because the change won't be visible to the caller). If you need to
    reassign the slice value itself, you'll need to pass in a pointer to it.

    On Sat, Dec 1, 2012 at 4:33 PM, Lukáš Zapletal wrote:

    Hello,

    I have a struct type and slice of the struct type:

    type Pair struct {
    fst byte
    snd byte
    status byte
    __align byte
    }

    type Pairs []Pair

    Now, is it okay to write my methods of Pairs as non pointers? I do not
    want any values to be copied, to me it looks like its fine and efficient
    because it's a slice:

    func (self Pairs) Match(other Pairs) float64 {

    Thanks

    xxx

    --

    --
  • Kevin Gillette at Dec 1, 2012 at 11:03 pm
    Note that your struct value is as small as a 32-bit pointer, so for read-only ops it is faster to do a value copy of that size. As long as you never need to grow or shrink the method receiver, you can use Pairs as you do now and the elements will be mutable.

    --

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedDec 1, '12 at 9:34p
activeDec 1, '12 at 11:03p
posts3
users3
websitegolang.org

People

Translate

site design / logo © 2022 Grokbase