Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a function that returns a slice of variable size in golang

I would like to build a function that returns a slice of any size. I know I can do

func BuildSlice() [100]int { return [100]int{} }

but I would like to be able to return slices of different sizes from the same function. Something like:

func BuildSlice(int size) [...]int { return [size]int{} }

I've tried the above as well as

func BuildSlice(size int) []int { return [size]int{} }

Please point me in the right direction.

Thanks.

like image 821
Daniel Nill Avatar asked Mar 11 '14 05:03

Daniel Nill


People also ask

How do you pass a slice to a function in Golang?

In Go language, you are allowed to pass a slice to a function, means the function gets the copy of the slice. Explanation: In the above example, we have a slice named as slc. This slice is passed in the myfun() function.

How do I declare a string slice in Golang?

A slice can be declare using new keyword followed by capacity in square brackets then type of elements the slice will hold.


2 Answers

The Go Programming Language Specification

Making slices, maps and channels

The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T). The memory is initialized as described in the section on initial values.

Call Type T Result

make(T, n)       slice      slice of type T with length n and capacity n
make(T, n, m)    slice      slice of type T with length n and capacity m

The size arguments n and m must be of integer type or untyped. A constant size argument must be non-negative and representable by a value of type int. If both n and m are provided and are constant, then n must be no larger than m. If n is negative or larger than m at run time, a run-time panic occurs.

s := make([]int, 10, 100)       // slice with len(s) == 10, cap(s) == 100
s := make([]int, 1e3)           // slice with len(s) == cap(s) == 1000
s := make([]int, 1<<63)         // illegal: len(s) is not representable by a value of type int
s := make([]int, 10, 0)         // illegal: len(s) > cap(s)

For example,

package main

import "fmt"

func main() {
    s := make([]int, 7, 42)
    fmt.Println(len(s), cap(s))
    t := make([]int, 100)
    fmt.Println(len(t), cap(t))
}

Output:

7 42
100 100
like image 37
peterSO Avatar answered Oct 12 '22 06:10

peterSO


First of all, slices are already of "variable size": [100]int and [...]int are array type definitions.

[]int is the correct syntax for a slice, and you could implement the function as:

func BuildSlice(size int) []int {
    return make([]int, size)
}

This will return a slice of zero values with the desired size, similar to what your array version does.

like image 150
James Henstridge Avatar answered Oct 12 '22 05:10

James Henstridge