Code Fix

初級

invalid operation: mismatched types string and int の原因と直し方

文字列と数値を+演算子でそのまま連結しようとすると、型が一致していないためコンパイルエラーになります。数値を文字列に変換してから連結する必要があります。

エラーメッセージの読み方

./main.go:11:14: invalid operation: label + num (mismatched types string and int)
./main.go
ファイル名
11
行番号
14
列番号
invalid operation: label + num (mismatched types string and int)
詳細メッセージ — 何が問題だったか

このエラーが出る典型パターン

パターン1

 1  package main
 2  
 3  import (
 4  	"fmt"
 5  	"strconv"
 6  )
 7  
 8  func main() {
 9  	label := "score: "
10  	num := 5
11  	fmt.Println(label + num              )
                             ^
12  }
./main.go:11:14: invalid operation: label + num (mismatched types string and int)

+でstringとintを直接連結することはできません。strconv.Itoaでnumを文字列に変換する必要があります。

直し方: label + numlabel + strconv.Itoa(num) にします。

この問題を解いてみる →

広告
広告スロット(未設定)

パターン2

 1  package main
 2  
 3  import (
 4  	"fmt"
 5  	"strconv"
 6  )
 7  
 8  func main() {
 9  	prefix := "age: "
10  	val := 20
11  	fmt.Println(prefix + val              )
                              ^
12  }
./main.go:11:14: invalid operation: prefix + val (mismatched types string and int)

string(val)はint型をrune(文字コード)として解釈してしまうため、意図した数値の文字列化にはなりません。strconv.Itoaを使う必要があります。

直し方: prefix + valprefix + strconv.Itoa(val) にします。

この問題を解いてみる →

パターン3

 1  package main
 2  
 3  import (
 4  	"fmt"
 5  	"strconv"
 6  )
 7  
 8  func main() {
 9  	msg := "total: "
10  	amount := 100
11  	fmt.Println(msg + amount              )
                              ^
12  }
./main.go:11:14: invalid operation: msg + amount (mismatched types string and int)

Goは暗黙の型変換を行わないため、+演算子の両辺は同じ型でなければなりません。

直し方: msg + amountmsg + strconv.Itoa(amount) にします。

この問題を解いてみる →

パターン4

 1  package main
 2  
 3  import (
 4  	"fmt"
 5  	"strconv"
 6  )
 7  
 8  func main() {
 9  	header := "id: "
10  	num := 7
11  	fmt.Println(header + num              )
                              ^
12  }
./main.go:11:14: invalid operation: header + num (mismatched types string and int)

数値をログメッセージなどに埋め込みたい場合は、必ずstrconv.Itoaなどで明示的に文字列へ変換します。

直し方: header + numheader + strconv.Itoa(num) にします。

この問題を解いてみる →

パターン5

 1  package main
 2  
 3  import (
 4  	"fmt"
 5  	"strconv"
 6  )
 7  
 8  func main() {
 9  	tag := "count: "
10  	n := 3
11  	fmt.Println(tag + n              )
                           ^
12  }
./main.go:11:14: invalid operation: tag + n (mismatched types string and int)

fmt.Printlnに複数の引数として渡す(tag, n)という書き方なら型変換無しでも動きますが、+で連結する場合は型を揃える必要があります。

直し方: tag + ntag + strconv.Itoa(n) にします。

この問題を解いてみる →

よくある誤解

「+は文字列と数値を渡せば、自動的に数値側を文字列に変換して連結してくれるはず」という思い込みは誤りです。Goは暗黙の型変換を行わないため、strconv.Itoaなどで明示的に文字列へ変換する必要があります。

まとめ

invalid operation: mismatched types string and intは初級でつまずきやすい項目です。上の5パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。

演習をはじめる

関連するエラー

広告
広告スロット(未設定)