14

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?

3
  • It's the Go programming language, not golang.
    – peterSO
    Jun 21, 2011 at 11:47
  • 8
    sorry about the golang - thought I was seeing that as a standard ref. the difference between goggling for "go" vs "golang" is huge, so have always tried to put the phrase "golang" as a courtesy, but open to suggestions
    – cc young
    Jun 21, 2011 at 13:05
  • If you want to force constructor, you should put your code in a separate package, expose public interface and a constructor that will return a private struct that implements the interface. Aug 15, 2016 at 8:55

4 Answers 4

10

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 ก
3
  • makes perfect sense (again). with so many languages and conflicting paradigms it's sometimes difficult to get into the right zone. still trying to wrap my mind around the whole interfaces. cool, but need a quantumly better understanding before it becomes organic.
    – cc young
    Jun 21, 2011 at 13:17
  • I get an error with this code: "cannot convert hello (type string) to type []int "
    – RoboTamer
    Aug 26, 2012 at 6:10
  • @RoboTamer use rune. It will work. You will notice that because you have used *Char a big number in hex gets printed: like 0x7f2814d0af64 (it's memory adress)
    – jpfreire
    May 8, 2013 at 23:28
2

At the first, see following example.

package main

func main() {
    s := "hello 世界"
    //for getting characters from string

    cells := []int(s)
    for _, c := range cells {
        println(c, string(c))
        // You'll get
        // 104 h
        // 101 e
        // 108 l
        // 108 l
        // 111 o
        // 32  
        // 19990 世
        // 30028 界
    }

    bytes := []byte(s)
    for _, b := range bytes {
        println(b, string(b))
        // 104
        // 101
        // 108
        // 108
        // 111
        // 32
        // 228
        // 184
        // 150
        // 231
        // 149
        // 140
    }
}

The meaning of []int(s) is "cast to unicode characters". The meaning of []byte(s) is "cast to bytes".

And, Go does not have constructor. In Go's style, package provide function NewXXX() for XXX object.

type Client struct {
    // ...
}

func NewClient() *Client {
    return &Client{/* ... */}
}

UPDATE:

If you mean Char as "1 element of string", you should define as following.

type Char int

Or

type Char byte

Your definition

type Char string

is re-define of "string". Then it can store string.

5
  • do not think I'm being very clear. in type Char string, string is the basetype, so one can say var c Char = "abc". then c == "abc" but that's wrong - need c == "a". I guess what I am wondering is if it's possible to intercept and/or disable Go's initial interpretation of var c Char = "abc" === c := Char("abc"), or if there are other more sensible approaches to this problem.
    – cc young
    Jun 21, 2011 at 9:19
  • thanks for the func NewType() Type Go style for a constructor
    – cc young
    Jun 21, 2011 at 9:22
  • missed your original intent - thanks. this is for a db interface, so (I think) char could be based on client encoding - a nasty problem I am cowardly ignoring for the time. but I think you're more right than I am and will be moving Char to uint, so thanks for that. do you have any ideas on the original question on how to keep the compiler from constructing types on its own and not going through the constructor?
    – cc young
    Jun 21, 2011 at 9:56
  • No, I don't have any idea. go does not have constructor.
    – mattn
    Jun 21, 2011 at 10:02
  • Char("foo") mean cast from string to Char. not a function call. If you want to create constructor(like) function, you should provide func NewChar.
    – mattn
    Jun 21, 2011 at 10:03
1

Along with the other answers, it should be noted that Go has no such thing as special constructor syntax. There are some conventions though. Generally when you have a custom type and need a constructor, you write a NewT() function which takes any parameters you need, performs initialization and returns one instance of said type.

type Char string

func NewChar(s string) Char {
    if len(s) == 0 {
       return Char("")
    }
    return Char(s[:1])
}
1
  • 1
    If a package t implements type T and there is only one constructor, the convention is to name it New so that it reads easily as t.New. For example: golang.org/search?q=New.
    – peterSO
    Jun 21, 2011 at 14:09
0

A single unicode character in Go is represented by a uint32 You could do the following:

type Char uint32
var a Char = 'a'

No need for a constructor, since you can just use the character literal.

1
  • should have seen this coming. let's say we want a type Char2 string where it will have exactly two characters, then how to solve the problem - or can it be solved? btw, string for user sanity, since in practice a db char is mostly used as a string.
    – cc young
    Jun 21, 2011 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.