Cast interface to Parametrized type from parameter

Hello
I need to cast an interface to the type passed as parameter. Something like this:

func Try(res interface{}, err error, t T) T {
	
	if err != nil {
		log.Print(err)
		os.Exit(-1)
	}
	
	return res.(T)
}

I need to manage, temporarily, errors in that way calling a function inside the Try function ( I know about error management, but it is temporary for now, and cast only the result value with the type passed as parameter. That code of course is not correct.

Is there a way in Golang to do that ?

Thank you

Not currently, though with Go 1.18 Generics will get introduced:

package main

import (
	"fmt"
	"log"
	"os"
)

func Try[T any](res T, err error) T {

	if err != nil {
		log.Print(err)
		os.Exit(-1)
	}

	return res
}

func main() {
	fmt.Println(Try(1, nil))
}
3 Likes