Defining new data types with generics
In this section we are going to create a new data type with the use of generics, which is presented in newDT.go
. The code of newDT.go
is the following:
package main
import (
"fmt"
"errors"
)
type TreeLast[T any] []T
The previous statement declares a new data type named TreeLast
that uses generics.
func (t TreeLast[T]) replaceLast(element T) (TreeLast[T], error) {
if len(t) == 0 {
return t, errors.New("This is empty!")
}
t[len(t) - 1] = element
return t, nil
}
replaceLast()
is a method that operates on TreeLast
variables. Apart from the function signature, there is nothing else that shows the use of generics.
func main() {
tempStr := TreeLast[string]{"aa", "bb"}
fmt.Println(tempStr)
tempStr.replaceLast("cc")
fmt.Println(tempStr)
In this first part of main()
, we create a TreeLast
variable with the aa
and bb
...