5

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

1
  • 2
    remove the [] in var queue []Queue, you'll still get runtime error though. Commented Feb 7, 2017 at 9:51

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

You are right, but now it's throwing: panic: runtime error: index out of range . I added queue = append(queue, job) and it's now working with the above modification. Thank you.
@TheodorB, quite right, because queue was just created and has no zeroth element. Using append add such element. Have you checked len and cap functions for slice?
Not yet but I will have a look. Thank you once again for the answer.
5

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

Comments

0

[]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"})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.