我的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)
}
我也尝试直接在Order中追加到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
问题是您试图将Orderline指针放入需要Orderline值的切片中。
type Order struct {
Id int64
Customer *Customer
Orderlines *[]Orderline
}
从更改此字段的类型
Orderlines *[]Orderline
至...
Orderlines []*Orderline
您还需要更改...
ols := []Orderline{&ol1, &ol2}
至
ols := []*Orderline{&ol1, &ol2}
在大多数情况下,定义* [] slicetype是多余的,因为slice,map和channel已经是引用类型。换句话说,如果将main中定义的slice的值传递给函数,则对复制的slice的索引所做的更改也会使main中定义的原始slice发生变化。
但是,请务必注意,由于将数据附加到切片而导致单个副本的基础阵列被迫增加其容量时,切片会彼此分离。因此,在某些情况下,您可能会找到指向理想切片甚至必要切片的指针。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句