Assigning values to an array of struct in Golang

0

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

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

The question is whether it is possible to do something of the type to fill the values or if there is any other way to do it

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

}
}
    
asked by anonymous 31.10.2018 / 22:39

1 answer

1

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

The iteration occurs in each slice item, so each p[i] is a process . Maybe this will 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)
}

You can test this here. For every p[i] there is a process . So using &p[1].burst[i] makes no sense, unless burst is also a slice or array. But, as it is int, it does not make sense.

    
02.11.2018 / 21:25