Skip to content
This repository has been archived by the owner on Sep 20, 2022. It is now read-only.

type switch #9

Open
glycerine opened this issue Jun 14, 2018 · 2 comments
Open

type switch #9

glycerine opened this issue Jun 14, 2018 · 2 comments
Assignees
Labels
enhancement New feature or request

Comments

@glycerine
Copy link

glycerine commented Jun 14, 2018

Can one type switch within the implementation of a generic function? something like this might be reasonable:

func add[T](a, b T) T {
  switch T { // equivalent to switch a.(type)
       case float64:
            return math.Round(a + b)
        case int64:
           return a+b
   }
}
@albrow albrow added the enhancement New feature or request label Jun 15, 2018
@albrow albrow self-assigned this Jun 15, 2018
@albrow
Copy link
Owner

albrow commented Jun 15, 2018

This is a good idea. We almost already have a way to do this right now.

Consider this Playground example:

package main

import "fmt"

func printType[T] (x T) {
	switch x := x.(type) {
	case int:
		fmt.Printf("int(%d)", x)
	case string:
		fmt.Printf("string(%s)", x)
	}
}

func main() {
	printType[int](42)
	printType[string]("hello")
}

Parsing and type-checking works fine. Type parameters are internally considered to have underlying type interface{} so you are allowed to use a type switch on them in the body of a function. But ultimately it fails because the generated Go code looks like this:

func printType__int (x int) {
	switch x := x.(type) {
	case int:
		fmt.Printf("int(%d)", x)
	case string:
		fmt.Printf("string(%s)", x)
	}
}

In Go, you can't use a type switch on non-interface types like int. However, it should not be too difficult for the Fo compiler to remove the type switch from the AST when it already knows the type. The generated Go code would then look like this:

func printType__int (x int) {
	fmt.Printf("int(%d)", x)
}

func printType_string(x string) {
	fmt.Printf("string(%s)", x)
}

@ncw
Copy link

ncw commented Jun 18, 2018

In Go, you can't use a type switch on non-interface types like int. However, it should not be too difficult for the Fo compiler to remove the type switch from the AST when it already knows the type.

You could also cast the parameter to an interface {}

    switch x := (interface {})(x).(type)

If that was easier - the go compiler will then prune the switch for you.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants