go – Change values of the pointer of slice in Golang-ThrowExceptions

Exception or error:

Have a slice with float64 values. And I want to multiply them without new memory allocation. Is it possible?

multiple(&slice)


func multiple(slice *[]float64) {

    for index, value := range *slice {
        ??? =  value * 100
    }
}
How to solve:

This should work:

func multiple(slice *[]float64) {

    for index, value := range *slice {
        (*slice)[index] =  value * 100
    }
}

You are passing a pointer to a slice. Are you sure that’s what you need? The following would also work:

func multiple(slice []float64) {

    for index, value := range slice {
        slice[index] =  value * 100
    }
}

When you pass *[]float64, the function gets a pointer to the slice. To work with the elements of the slice, the function has to dereference the pointer, then dereference the array pointed to by the slice.

When you pass []float64, the function gets a slice, which contains a pointer to the underlying array, length, and capacity.

Leave a Reply

Your email address will not be published. Required fields are marked *