more advanced usage for ~

tags: learning go programming

content

in this function:

go-type-inference-1#type-infer

how to make ms2 the same type as ms?

  • i.e., how to make Clone return the same type as its input argument?
  1. the signature of Clone should be something like:
    • func Clone[TempType any](s TempType) TempType {}
    • now the input and output are matching, both are TempType
    • Clone becomes
func Clone[TempType any](s TempType) TempType {
	return append(TempType(nil), s...)  // error!
}
  1. but we are calling append with TempType
    • append expects a
    • the signature of append is:
func append(slice []Type, elems ...Type) []Type
  1. we have to make TempType in Clone a slice!
func Clone[TempType []?](s TempType) TempType { /*...*/ }
  • what should be the ?, should be anything!
  1. make TempType a 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 ms is NOT a slice
  • we still need Go to infer the underlying type of MySlice
  1. 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...)
}

up

down

reference