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?
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.
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.
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.
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.
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 ก
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With