Thanks Jan & Peter. I would use one of the approaches.

On Thursday, November 7, 2019 at 8:15:20 AM UTC-5, speter wrote:
>
> Hi bsr,
>
> I'd suggest to use a struct type with a single string field. It will 
> prevent conversion from untyped string constant "by mistake".
> Moreover, if you make the string field unexported, you can limit new 
> instance creation to the declaring package, allowing to enforce predefined 
> values.
> Unlike with some other languages, there is no memory or runtime overhead 
> due to encapsulating the string within a struct.
>
> HTH,
> Peter
>
> On Thu, Nov 7, 2019 at 7:58 PM bsr <bsr...@gmail.com <javascript:>> wrote:
>
>> Hello,
>>
>> I am a long time user of go, but I always had the impression that below 
>> code would not work as string and Status are different type.
>> I thought I need to explicitly convert as ```exec(Status("abc"))``` it to 
>> work.
>>
>> I think, this part of the spec may be the reason 
>> https://golang.org/ref/spec#Assignability
>>
>>    - x is an untyped constant <https://golang.org/ref/spec#Constants> 
>>    representable <https://golang.org/ref/spec#Representability> by a 
>>    value of type T. 
>>
>> Is there a way I can prevent this behavior.
>> I am using Status like an enum, and only predefined status values should 
>> be allowed.
>>
>>
>>
>>
>> https://play.golang.org/p/4zsb7KtPBC6
>>
>> package main
>>
>> import (
>>     "fmt"
>> )
>>
>> type Status string
>>
>> func main() {
>>     exec("abc")
>> }
>>
>> func exec(s Status) {
>>     fmt.Printf("Hello, %s", s)
>> }
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to golan...@googlegroups.com <javascript:>.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/golang-nuts/a20a7034-19c3-410a-bc86-25deff38534f%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/a20a7034-19c3-410a-bc86-25deff38534f%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/6c2b95f5-5e22-4d3b-bf1c-b44920213a1c%40googlegroups.com.

Reply via email to