cannot use i % 3 == 0 (type untyped bool) as type int

135 阅读1分钟

报错代码

package main

import "fmt"

func main() {
	g(15)
}

func g(i int) {
	switch i{
	case i%3==0:
		fmt.Print("Fizz")
	case i%5==0:
		fmt.Print("Buzz")
	case i%3==0 && i%5==0:
		fmt.Print("FizzBuzz")
	}
}

报错信息

./main.go:12:2: cannot use i % 3 == 0 (type untyped bool) as type int
./main.go:14:2: cannot use i % 5 == 0 (type untyped bool) as type int
./main.go:16:2: cannot use i % 3 == 0 && i % 5 == 0 (type bool) as type int

报错原因switch使用方式错误,修改方法,把i改为true或去掉i

package main

import "fmt"

func main() {
	g(15)
}

func g(i int) {
	switch {
	case i%3==0:
		fmt.Print("Fizz")
	case i%5==0:
		fmt.Print("Buzz")
	case i%3==0 && i%5==0:
		fmt.Print("FizzBuzz")
	}
}