Created
July 3, 2022 06:25
-
-
Save tuncatunc/e6dd6a4942548f58212c9b4e2889646f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// List represents a singly-linked list that holds | |
// values of any type. | |
type List[T comparable] struct { | |
next *List[T] | |
val T | |
} | |
type ListError struct { | |
msg string | |
} | |
func (e ListError) Error() string { | |
return "List Error" | |
} | |
func (self *List[T]) find(val T) (T, error){ | |
item := self | |
for item != nil { | |
if item.val == val { | |
return item.val, nil | |
} | |
item = item.next | |
} | |
return val, ListError{"Item not found"} | |
} | |
func main() { | |
list := List[int]{&List[int]{nil, 2}, 1} | |
val, _ := list.find(1) | |
fmt.Println(val) | |
val1, _ := list.find(2) | |
fmt.Println(val1) | |
val2, err := list.find(3) | |
fmt.Println(err, val2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment