Golang Slice of custom键入另一个Type作为参考

时间:2014-02-07 15:47:17

标签: reference go

我的Go测试代码出现此错误:

$ 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

代码

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)
}

我也尝试直接附加到订单中的Slice,但它也失败了:

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

抛出:

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

1 个答案:

答案 0 :(得分:2)

问题在于您尝试将Orderline指针放入需要Orderline值的切片中。

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

更改此字段的类型

Orderlines *[]Orderline

为...

Orderlines []*Orderline

您还需要更改...

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

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

在大多数情况下,定义* [] slicetype是多余的,因为切片,贴图和通道已经是引用类型。换句话说,如果将main中定义的切片值传递给函数,对复制切片索引所做的更改也会改变main中定义的原始切片。

但是,重要的是要注意,当单个副本的基础数组因为向切片附加数据而强制增加其容量时,切片会彼此分离。因此,在某些情况下,您可能会发现指向切片的指针是理想的甚至是必要的。