In Go, how do I create a "constructor" for a type with a string base type?

Viewed 10467

trying to have a type Char that is a string one character long. what I'm unable to do is create a "constructor". I know I'm missing something completely obvious.

declare the Char type

  type Char string

can use that type with a declaration

  var c1 Char("abc")
  var c2 Char = "abc"

these are wrong: c1 and c2 need to be "a", not "abc"

what I really want is a "constructor" to limit Char to one character

 func Char( s string ) Char {
   var ch string = s[0]
   return ch
 }

of course having the type Char and func Char is not the way to do it

 type.go:8: Char redeclared in this block

is there any way for to force type initialization through a constructor? or am I even asking the correct question?

let me state differently: if the user says var c Char = "abc" they will have an invalid value for type Char - is there any way to force the user into func NewChar(string) Char as Char's only valid constructor?

4 Answers
Related