Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 517
cc young Avatar asked Jun 21 '11 05:06

cc young


People also ask

Does golang have constructors?

There are no default constructors in Go, but you can declare methods for any type. You could make it a habit to declare a method called "Init". Not sure if how this relates to best practices, but it helps keep names short without loosing clarity.

What does string mean in Golang?

In Go language, strings are different from other languages like Java, C++, Python, etc. it is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.

What is Type Golang?

Type is the base interface for all data types in Go. This means that all other data types (such as int , float , or string ) implement the Type interface. Type is defined in the reflect header.

What does New do in Golang?

New() Function in Golang is used to get the Value representing a pointer to a new zero value for the specified type. To access this function, one needs to imports the reflect package in the program.


1 Answers

This is the char package. Note the unexported Char struct field c.

package char

type Char struct {
    c rune
}

func New(c rune) *Char {
    return &Char{c}
}

func (c *Char) Char() rune {
    return c.c
}

func (c *Char) String() string {
    return string(c.c)
}

Here's an example of how to use the char package.

package main

import (
    "char"
    "fmt"
)

func main() {
    var c = char.New('z')
    var d = c.Char()
    hello := "Hello, world; or สวัสดีชาวโลก"
    h := []rune(hello)
    ก := char.New(h[len(h)-1])
    fmt.Println(c, "a-"+c.String(), '0' <= d && d <= '9', ก)
}

Output:

z a-z false ก
like image 147
peterSO Avatar answered Oct 13 '22 07:10

peterSO