dsgni26260 2014-02-07 15:47
浏览 67
已采纳

自定义类型的Golang切片在另一个类型中作为参考

I get this error with my Go test code:

$ go run test.go 
# command-line-arguments
./test.go:43: cannot use &ol1 (type *Orderline) as type Orderline in array element
./test.go:43: cannot use &ol2 (type *Orderline) as type Orderline in array element

Code

package main

import (
    "fmt"
)

type Customer struct {
    Id int64
    Name string
}

type Order struct {
    Id int64
    Customer *Customer
    Orderlines *[]Orderline
}

type Orderline struct {
    Id int64
    Product *Product
    Amount int64
}

type Product struct {
    Id int64
    Modelnr string
    Price float64
}

func (o *Order) total_amount() float64 {
    return 0.0 // Total amount collector for each Orderline goes here
}

func main() {
    c := Customer{1, "Customername"}

    p1 := Product{30, "Z97", 9.95}
    p2 := Product{31, "Z98", 25.00}

    ol1 := Orderline{10, &p1, 2}
    ol2 := Orderline{11, &p2, 6}

    ols := []Orderline{&ol1, &ol2}

    o := Order{1, &c, &ols}

    fmt.Println(o)
}

I also tried to append to the Slice in the Order directly, but it also failed:

o := new(Order)
o.Id = 1
o.Customer = &c
append(o.Orderlines, &ol1, &ol2)

throws:

$ go run test.go 
# command-line-arguments
./test.go:48: append(o.Orderlines, &ol1, &ol2) evaluated but not used
  • 写回答

1条回答 默认 最新

  • dongxia2068 2014-02-08 14:06
    关注

    The problem is that you are trying to put Orderline pointers into a slice that wants Orderline values.

    type Order struct {
        Id int64
        Customer *Customer
        Orderlines *[]Orderline
    }
    

    Change this field's type from

    Orderlines *[]Orderline

    to...

    Orderlines []*Orderline

    You also need to change...

    ols := []Orderline{&ol1, &ol2}

    to

    ols := []*Orderline{&ol1, &ol2}

    In most cases defining a *[]slicetype is redundant because slices, maps, and channels are already reference types. In otherwords if you pass the value of a slice defined in main into a function, changes made to the copied slice's indices will mutate the original slice defined in main as well.

    However, it's important to note that slices become decoupled from each other when an individual copy's underlying array is forced to grow it's capacity as a result of appending data to your slice. Therefore in certain scenarios you may find a pointer to a slice ideal or even necessary.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配