Search code examples
gocastingtype-conversionslice

Function to Convert int slice to Custom int slice pointer type in Go


I want to take an int slice as an input to a constructor and return a pointer to the original list, type casted into my external custom type(type IntList []int).

I can do this:

type IntList []int

func NewIntListPtr(ints []int) *IntList {
    x := IntList(ints)
    return &x
}

But I cannot do this:

type IntList []int

func NewIntListPtr(ints []int) *IntList {
    return &ints
}

// or this for that matter:

func NewIntListPtr(ints []int) *IntList {
    return &(IntList(ints))
}

// or this

func NewIntListPtr(ints []int) *IntList {
    return &IntList(*ints)
}

// or this

func NewIntListPtr(ints *[]int) *IntList {
    return &(IntList(*ints))
}

Is there a one-liner to achieve the this?


Solution

  • You do it like this:

    func NewIntListPtr(ints []int) *IntList {
        return (*IntList)(&ints)
    }