How to constraint type parameter not pointer

165 views
Skip to first unread message

李晓辉

unread,
Mar 18, 2023, 6:37:59 AM3/18/23
to golang-nuts
When I want to implement a Maybe[T any] type, the T can't be nil, but I can't find way to constraint this, can anyone give helps.

Brian Candler

unread,
Mar 18, 2023, 7:25:43 AM3/18/23
to golang-nuts
AFAIK you can't.

1. T only constrains the type, not its value.  If the type is nillable, then nil is one of its valid values.

2. in [T any], T could be any type, including types which are not nillable (e.g. int).  So you can't compare the value to nil inside the generic function - although you could check for the *zero* value (using "var zero T" and compare with that)

TheDiveO

unread,
Mar 18, 2023, 2:00:03 PM3/18/23
to golang-nuts
Maybe (no pun intended) implementations like https://github.com/OlegStotsky/go-monads and https://github.com/TeaEntityLab/fpGo can shed some more light on your question and implementation designs?

TheDiveO

unread,
Mar 18, 2023, 2:02:00 PM3/18/23
to golang-nuts
How could I forget https://github.com/samber/mo...?

李晓辉

unread,
Mar 19, 2023, 10:52:14 AM3/19/23
to golang-nuts
To be honest, no, if I set T to *int, then get will return *int, not int, so T must not be nillable type.
Reply all
Reply to author
Forward
0 new messages