duanhui1869 2019-07-06 10:48
浏览 64
已采纳

初始化指针数组-无法使类型* [] 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
}
  • 写回答

2条回答 默认 最新

  • dongshukou0240 2019-07-06 12:12
    关注

    Changing this would make your code work:

    tCars := make([]car, 4)
    _cars = &tCars
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答