Closed3

Golangの型変換について

Nozo-MacNozo-Mac

https://go.dev/ref/spec#Min_and_max を読んでいて引数に異なる型が入っており不思議に感じたため調査をする。

package main

import (
  "fmt"
)

func main() {
  // Arrange
  one := 1
  zero_point_one := 0.1
  // Check type
  fmt.Printf("Type of one: %T\n", one)
  fmt.Printf("Type of zero_point_one: %T\n", zero_point_one)

  // min_value := min(zero_point_one, one) // Failed : invalid argument: mismatched types float64 (previous argument) and int (type of one)
  // max_value := max(zero_point_one, one) // Failed : invalid argument: mismatched types float64 (previous argument) and int (type of one)
  min_value := min(1, 0.1)
  max_value := max(1, 0.1)
  fmt.Println("Min:", min_value)
  fmt.Println("Max:", max_value)
  // Check type
  fmt.Printf("Type of min_value: %T\n", min_value)
  fmt.Printf("Type of max_value: %T\n", max_value)
}



❯ go run main.go
Type of one: int
Type of zero_point_one: float64
Min: 0.1
Max: 1
Type of min_value: float64
Type of max_value: float64

Nozo-MacNozo-Mac

ちなみに上のところのコメントアウトを逆にすると失敗する:

package main

import (
  "fmt"
)

func main() {
  // Arrange
  one := 1
  zero_point_one := 0.1
  // Check type
  fmt.Printf("Type of one: %T\n", one)
  fmt.Printf("Type of zero_point_one: %T\n", zero_point_one)

  min_value := min(zero_point_one, one) // Failed : invalid argument: mismatched types float64 (previous argument) and int (type of one)
  max_value := max(zero_point_one, one) // Failed : invalid argument: mismatched types float64 (previous argument) and int (type of one)
  // min_value := min(1, 0.1)
  // max_value := max(1, 0.1)
  fmt.Println("Min:", min_value)
  fmt.Println("Max:", max_value)
  // Check type
  fmt.Printf("Type of min_value: %T\n", min_value)
  fmt.Printf("Type of max_value: %T\n", max_value)
}

❯ go run main.go
# command-line-arguments
./main.go:15:36: invalid argument: mismatched types float64 (previous argument) and int (type of one)
./main.go:16:36: invalid argument: mismatched types float64 (previous argument) and int (type of one)
Nozo-MacNozo-Mac

詳細挙動を理解しきれていないですが同じ型ではないと動作しないことがわかったため閉じます。

このスクラップは6ヶ月前にクローズされました