[英]Golang Slice of custom Type in another Type as reference
I get this error with my Go test code: 我的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
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: 我也尝试直接附加到订单中的Slice,但它也失败了:
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
The problem is that you are trying to put Orderline pointers into a slice that wants Orderline values. 问题是您正在尝试将Orderline指针放入需要Orderline值的切片中。
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. 在大多数情况下,定义* [] slicetype是多余的,因为切片,贴图和通道已经是引用类型。 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.
换句话说,如果将main中定义的切片的值传递给函数,则对复制的切片索引所做的更改也会改变main中定义的原始切片。
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.
因此,在某些情况下,您可能会发现指向切片的指针是理想的甚至是必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.