Why doesn’t a type switch case with multiple types assign the detected type to the variable?

  Kiến thức lập trình

In Go, I want to understand some design choices in the type switch. The following example works as expected:

package main

import "fmt"

func abs[T int | float64](a T) T {
    if a >= 0 {
        return a
    }
    return -a
}

func main() {
    a := -1.1
    switch b := any(a).(type) {
    case int:
        fmt.Println(abs(b))
    case float64:
        fmt.Println(abs(b))
    }
}

However, this similar example does not work:

package main

import "fmt"

func abs[T int | float64](a T) T {
    if a >= 0 {
        return a
    }
    return -a
}

func main() {
    a := -1.1
    switch b := any(a).(type) {
    case int, float64:
        // not working because b keeps the type of a
        fmt.Println(abs(b))
    }
}

I understand that this behavior is expected according to the specification, but why is it designed this way? Specifically, why isn’t the following:

case T1, T2, ...:
// some code

equivalent to:

case T1:
// some code
case T2:
// some code (the same)
...

What is the reasoning behind this design choice in Go’s type switch?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT