more advanced usage for ~
tags: learning go programming
content
in this function:
go-type-inference-1#type-infer
ms2is type[]string, see go-type-inference-1 for explanation
how to make ms2 the same type as ms?
- i.e., how to make
Clonereturn the same type as its input argument?
- the signature of
Cloneshould be something like:func Clone[TempType any](s TempType) TempType {}- now the input and output are matching, both are
TempType Clonebecomes
func Clone[TempType any](s TempType) TempType {
return append(TempType(nil), s...) // error!
}- but we are calling
appendwithTempTypeappendexpects a- the signature of
appendis:
func append(slice []Type, elems ...Type) []Type- we have to make
TempTypeinClonea slice!
func Clone[TempType []?](s TempType) TempType { /*...*/ }- what should be the
?, should be anything!
- make
TempTypea slice of any type:
func Clone[TempType []E, E any](s TempType) TempType {
return append(TempType(nil), s...)
}- now if we pass in:
type MySlice []string
ms := MySlice{"hello", "world"}
ms2 := Clone(ms)- it’s still not working, because
msis NOT a slice - we still need Go to infer the underlying type of
MySlice
- that’s where we have
~
- ask Go to infer the underlying type of
TempType - use
TempType ~[]E
func Clone[TempType ~[]E, E any](s TempType) TempType {
return append(TempType(nil), s...)
}