[英]golang type array containing structs
I am trying to create a pseudo queue structure and insert jobs structs inside it. 我试图创建一个伪队列结构,并在其中插入作业结构。 What am I doing wrong ? 我究竟做错了什么 ?
import "fmt"
type Job struct {
Type string
Url string
}
type Queue [] Job
func main() {
var queue []Queue
job := Job{"test", "http://google.com"}
queue[0] = job
fmt.Println(queue)
}
The code above is throwing: 上面的代码抛出:
cannot use job (type Job) as type Queue in assignment 不能在分配中使用作业(作业类型)作为队列类型
You don't need a slice of queues, and you should not index an empty slice. 您不需要队列片,也不应索引空片。
package main
import "fmt"
type Job struct {
Type string
Url string
}
type Queue []Job
func main() {
var q Queue
job := Job{"test", "http://google.com"}
q = append(q, job)
fmt.Println(q)
}
I think problem is here: 我认为问题出在这里:
var queue []Queue
Here queue
is a slice of Queue
or slice of slice of Job
. 这里queue
是Queue
或Job
。 So it's impossible to assign first its element value of Job
. 因此,不可能首先分配Job
元素值。
Try: 尝试:
var queue Queue
[]TypeName
is definition of slice of TypeName
type. []TypeName
是TypeName
类型的slice的定义。
Just as it said: 就像它说的那样:
var queue []Queue
is a slice of instances of type Queue
. var queue []Queue
是Queue
类型的实例的一部分。
q := Queue{Job{"test", "http://google.com"}, Job{"test", "http://google.com"}}
Definitely it is not what you want. 绝对不是您想要的。 Instead of it you should declare var queue Queue
: 代替它,您应该声明var queue Queue
:
var queue Queue
q := append(queue, Job{"test", "http://google.com"}, Job{"test", "http://google.com"})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.