bthe0
bthe0

Reputation: 1434

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

Upvotes: 5

Views: 20735

Answers (3)

I159
I159

Reputation: 31189

[]TypeName is definition of slice of TypeName type.

Just as it said:

var queue []Queue is a slice of instances of type 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
q := append(queue, Job{"test", "http://google.com"}, Job{"test", "http://google.com"})

Upvotes: 0

dev.bmax
dev.bmax

Reputation: 11131

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

Upvotes: 5

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12875

I think problem is here:

var queue []Queue

Here queue is a slice of Queue or slice of slice of Job. So it's impossible to assign first its element value of Job.

Try:

var queue Queue

Upvotes: 6

Related Questions