Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add an example for operator '~' #482

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions examples/generics/generics.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,36 @@ package main

import "fmt"

type MyInt16 int16
type MyInt int

func (m MyInt16) String() string {
return fmt.Sprintf("{MyInt16: %d}", m)
}

func (m MyInt) String() string {
return fmt.Sprintf("{MyInt: %d}", m)
}

// `~` the underlying type of T must be itself, and T cannot be an interface.
type Number interface {
int | ~int16
}

// An interface representing all types with underlying type int that implement the String method.
type IntString interface {
~int16
String() string
}

func SumNumber[T Number](a, b T) T {
return a + b
}

func SumIntString[T IntString](a, b T) (T, string) {
return a + b, a.String() + ", " + b.String()
}

// As an example of a generic function, `MapKeys` takes
// a map of any type and returns a slice of its keys.
// This function has two type parameters - `K` and `V`;
Expand Down Expand Up @@ -71,4 +101,13 @@ func main() {
lst.Push(13)
lst.Push(23)
fmt.Println("list:", lst.GetAll())

// We can use `MyInt16` as the parameter of the function `SumNumber`, because its underlying type is int16.
fmt.Println(SumNumber(MyInt16(1), MyInt16(2)))
fmt.Println(SumNumber(1, 2))

// We can't use `MyInt` as the parameter of the function `SumInString`, because underlying type of `MyInt` is int not int16.
// also int16 does not implement `IntString` (missing method String).
result, str := SumIntString(MyInt16(1), MyInt16(2))
fmt.Printf("result: %d, output: %s\n", result, str)
}
4 changes: 2 additions & 2 deletions examples/generics/generics.hash
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
91465956a90881ec8b4cca3968b9aa1f6d9f1447
uXlb-AyeYmQ
58327cbd52a273bbf23034c16cc679e7dbffdd77
hw05lSyEz41
3 changes: 3 additions & 0 deletions examples/generics/generics.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
$ go run generics.go
keys: [4 1 2]
list: [10 13 23]
{MyInt16: 3}
3
result: 3, output: {MyInt16: 1}, {MyInt16: 2}
124 changes: 119 additions & 5 deletions public/generics

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.