Wednesday, September 18, 2024
HomeGolangI do not perceive typeparams - Getting Assist

I do not perceive typeparams – Getting Assist


Hello, I don’t know the connection of typeparams to sort switches, and typeparams as factor for quick code.

I’m on the lookout for the Go equal to C++ operate overloading and C++ resolving the categories at compile-time.

Might I publish a C++ instance that I wish to implement in Go?

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

So, if I need this instance from above in Go, with sort checking at runtime (sluggish, undesirable), I can write:

func foo(a interface{}) {
	swap v := i.(sort) {
	case int:
	case float32:
	default:
	}
}

That’s previous Go, and now in new Go I can even write (quick) code like this?

func foo[T any](a T) {
	swap v := a.(sort) {
	case int:
	case float32:
	default:
	}
}

This seems to be like there could be sort checking at runtime (undesirable), and perhaps the kind swap won’t compile. Ought to have checked it myself however I must study generic Go basically, so I’m asking.

I’ve not learn the proper design doc within the Go documentation. I’m undecided what the Go group tried to resolve and what not. I attempted to make use of any operate overloading which may have been in Go and the compiler advised me I’m redeclaring features and this isn’t the way it goes.

Go doesn’t have operate overloading, so the reply will depend on what foo(int) and foo(float) do. If they’ve totally different implementations, e.g.:

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

Then they need to be separate features in Go:

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

In the event that they each do the identical factor, simply with differing types, then I feel the Go 1.18+ approach to do that could be to make use of generics with a kind constraint:

sort intOrFloat32 interface  float32


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

1 Like

Thanks a lot.

One thing of the generics or constraints that Go 1.18 introduces is a bit arduous to understand, and it leads me into varied instructions, and to be trustworthy it’s possible that I’ll favor that C-style with out the brand new generics. I merely don’t know the design standards they adopted, and the code seems to be like I can’t perceive it with out investing months and years.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments