| question for experienced go devs: how do you deal with the lack of optional type or narrowing? from what i understand, pointers become used for that purpose instead (in addition to mutability). which then means that when you get a pointer you don’t know for what reason it is used, so you have to check it even if it was checked higher up in the callstack already. i wouldn’t actually mind the fact that you can forget to check for nil, i can accept a panic here and there, pretty simple to fix.. the issue i am finding is that it "pollutes" the code, since you end up doing the check more than once for the same value. if atleast you could only check once and then the compiler would know (ie optionals, or narrowing like TS). ideally you would dereference after the check, but you can’t because pointers are used for mutability AND optionals in other words, are there any tricks so that you only have to check once? |
Other than that though, I would say pointers are a last resort for indicating optional (I certainly do use them for this, but uncommonly). Idiomatic Go I think would suggest you use the empty value (I would use an empty value plus an // Optional comment).
Using pointers in general is fairly uncommon in the Go code I write - I don't often need the mutability as you say, because I try to stick to pure functions.
My thinking also, regardless of the language: be suspicious of a function that accepts an optional type. One should ask: is there a non short-circuit or non-error path in the empty case? If not, don't pass an optional, unwrap up the chain. Even if there is a valid path for an empty value, perhaps ask if the function should be split into two cleaner functions.