初始化指针数组-无法使类型* [] type

Its a simple code, saving car type objects into a car type array. I am trying to use pointer here to pass array reference.

There are 2 problems:

1 - I can't initialize it as empty array. When I use make, it says:

cannot make type *[]car

2 - If I don't use make, runtime error occurs:

panic: runtime error: invalid memory address or nil pointer dereference


Code:

import "fmt"

type car struct {
    plate string
    color string
}

func main() {

    var _cars *[]car        // list of cars
    _cars = make(*[]car, 4) // initialize empty cars list

    saveCar(_cars, car{"ABC-123", "Black"})
    saveCar(_cars, car{"ABC-456", "Black"})
    saveCar(_cars, car{"ABC-789", "Black"})

    fmt.Println(_cars)
}

func saveCar(_cars_list *[]car, _car car) int {

    for index, current := range *_cars_list {
        // if empty place found, save car
        if (car{}) == current {

            // save car
            (*_cars_list)[index] = _car

            // return the saved index
            return index
        }
    }

    return -1
}

Changing this would make your code work:

tCars := make([]car, 4)
_cars = &tCars

1 - cannot make type *[]car

You observe it because make creates slice, map or chan. In the example you gave you tried to create pointer to a slice which is none of the typed make works with.

2 - If I don't use make, runtime error occurs:

that's another problem - you have type "pointer to a slice of car", not "a slice of car". And in general you need to initialize pointer types before using.

Overall there is no need to use pointer to a slice rather than plain slice in your case, because you don't use append, to there is no chance for reallocation of backed storage.

However, in a real world scenario, when you don't know amount of car instances you are going to add, is much better to use append instead of iterating through slice till the last non-initialized value.

summary: