Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What cases "cannot convert "%d" (type untyped string) to type int" in Go?

Tags:

arrays

go

package main

import (
    "fmt"
)

func printArray(x [3]int) {
    fmt.Printf("%d", x[1]);
    // cannot convert "%d" (type untyped string) to type int
    // invalid operation: "%d" + v (mismatched types string and int)
    // for _, v := range x {
    //  fmt.Printf("%d" + v);
    // }
}

func main() {
    a := [3]int{1, 2, 3};

    for _, v := range a {
        fmt.Printf("%d\n", v);
    }

    printArray(a); 
}

I can successfully print the array in the go method, but when I pass array into the method, it throws an error when it tries to print. What cause's the method to treat it differently then main method?

like image 355
Tanvi Jaywant Avatar asked Aug 31 '25 16:08

Tanvi Jaywant


1 Answers

I see your error now. You are trying to concatenate or add the string and the int, instead of passing the two arguments to the function.

for _, v := range x {
   fmt.Printf("%d" + v); // The error is in this line
}

It should be:

func printArray(x [3]int) {
    for _, v := range x {
       fmt.Printf("%d", v);
    }
}
like image 198
Topo Avatar answered Sep 02 '25 06:09

Topo