Slice inside struct, cannot use type int64 as int in slice literal

I'm trying to get the user input at first.

The input at this stage should be a single uint to proceed but however, if user input is 2 then I want to let my program to create 2 triangles with additional 2 user inputs that will have a form of (int int int float). E.g.) 3 2 3 0.4.

So I create triangle struct, that has sides slice and Gs which refers to grey scale, you don't have to worry about the grey scale now. So here is my code:

type triangle struct {
    Sides []int
    Gs    float64
}

func main() {
    var triangles []triangle

    scanner := bufio.NewScanner(os.Stdin)

    var number int
    fmt.Scan(&number)

    i := 0
    for i < number+1 {
        scanner.Scan()
        in := scanner.Text()

        if len(in) != 0 {
        triangleDef := strings.Split(in, " ")
        s1, _ := strconv.ParseInt(triangleDef[0], 10, 32)
        s2, _ := strconv.ParseInt(triangleDef[1], 10, 32)
        s3, _ := strconv.ParseInt(triangleDef[2], 10, 32)
        gs, _ := strconv.ParseFloat(triangleDef[3], 64)
        // fmt.Println(s1, s2, s3, gs)
        triangle := triangle{Sides: []int{s1, s2, s3}, Gs: gs}
        triangles = append(triangles, triangle)
    }
    i++
}

But at the line 45, triangle := triangle{Sides: []int{s1, s2, s3}, Gs: gs}, it keeps returning an error saying "cannot type int64 as int in slice literal" for all s1, s2 and s3. What am I supposed to do to make it work?

1 answer

  • answered 2020-10-01 06:17 L Lawliet

    strconv.ParseInt returns an int64, which is a different type than int. You have to convert your variables to int to put them in a slice of ints.

    triangle := triangle{Sides: []int{int(s1), int(s2), int(s3)}, Gs: gs}
    

    See: https://tour.golang.org/basics/13