Wednesday, March 22, 2023
HomeGolangI don't understand typeparams - Getting Help

I don’t understand typeparams – Getting Help

Hi, I don’t know the relationship of typeparams to type switches, and typeparams as thing for fast code.

I’m looking for the Go equivalent to C++ function overloading and C++ resolving the types at compile-time.

May I post a C++ example that I want to implement in Go?

foo(int a) { /* do int things */ }
foo(float a) { /* do float things */ }

So, if I want this example from above in Go, with type checking at runtime (slow, unwanted), I can write:

func foo(a interface{}) {
	switch v := i.(type) {
	case int:
	case float32:

That is old Go, and now in new Go I can also write (fast) code like this?

func foo[T any](a T) {
	switch v := a.(type) {
	case int:
	case float32:

This looks like there would be type checking at runtime (unwanted), and maybe the type switch will not compile. Should have checked it myself but I need to learn generic Go in general, so I’m asking.

I have not read the right design document in the Go documentation. I’m not sure what the Go team tried to solve and what not. I tried to use any function overloading that might have been in Go and the compiler told me I’m redeclaring functions and this is not how it goes.

Go does not have function overloading, so the answer depends on what foo(int) and foo(float) do. If they have different implementations, e.g.:

int foo(int a) { return a + a; }
float foo(float a) { return a * a; }

Then they should be separate functions in Go:

func fooInt(a int) { return a + a }
func fooFloat(a float32) { return a * a }

If they both do the same thing, just with different types, then I think the Go 1.18+ way to do this would be to use generics with a type constraint:

type intOrFloat32 interface {
    int | float32

func foo[T intOrFloat32](a T) { return a * a }

1 Like

Thank you so much.

Something of the generics or constraints that Go 1.18 introduces is a bit hard to grasp, and it leads me into various directions, and to be honest it’s likely that I will prefer that C-style without the new generics. I simply don’t know the design criteria they followed, and the code looks like I will not understand it without investing months and years.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.


Most Popular

Recent Comments