Assign values to a struct array in Golang

Asked

Viewed 522 times

0

I’m starting to learn go and need to populate the different structs with their values. I thought about creating an array of structs and trying to use a for to fill the fields but give an error of

invalid operation: p[1].burst[i] (type int does not support indexing)

The question is whether it is possible to do something of the kind to fill the values or if there is some other way of doing

package main
import (

    "fmt"

)

type process struct{
     burst int
     t_chegada int
}

func main(){

p := make([]process,10)

var n_processo int
fmt.Printf("Número de Processo: ")
fmt.Scanf("%d", &n_processo)

for i := 0; i < n_processo; i++ {
    fmt.Printf("Burst Processo P%d: ", i)
    fmt.Scanf("%d\n", &p[1].burst[i])
    fmt.Printf("Tempo de Chegada  P%d: ", i)
    fmt.Scanf("%d\n", &p[2].t_chegada[i])

}
}

1 answer

2


You must use &p[i].burst and not &p[1].burst[i]:

for i := 0; i < n_processo; i++ {
    fmt.Printf("Burst Processo P%d: ", i)
    fmt.Scanf("%d\n", &p[i].burst)
    fmt.Printf("Tempo de Chegada  P%d: ", i)
    fmt.Scanf("%d\n", &p[i].t_chegada)
}

Iteration occurs on each item of the Slice, then each p[i] is a process. Maybe it’ll make it easier to understand:

package main
import (
    "fmt"
    mathrand "math/rand"
)

type process struct {
    burst     int
    t_chegada int
}

func main() {

    p := make([]process, 10)
    for i := range p {
        p[i] = process{
            burst:     mathrand.Int(),
            t_chegada: i,
        }
    }

    fmt.Print(p)
}

It is possible to test it here. For each p[i] there is a process. Then use the &p[1].burst[i] doesn’t make any sense, except if the burst also be a Slice or array. But since it’s int, it doesn’t make sense.

  • I was having trouble understanding a little how it worked and your answer helped a lot. I was having trouble reading the user input and put fmt.Scanf for every i do. I don’t know if it’s the best way but it worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.