在Go中,如何为具有字符串基本类型的类型创建一个“构造函数”?

huangapple go评论71阅读模式
英文:

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

问题

尝试创建一个类型为Char的字符串,长度为一个字符。我无法创建一个"构造函数"。我知道我漏掉了一些非常明显的东西。

声明Char类型

type Char string

可以使用该类型进行声明

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

这些是错误的:c1c2需要是"a",而不是"abc"。

我真正想要的是一个"构造函数"来限制Char只能有一个字符

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

当然,拥有type Charfunc Char不是解决问题的方法

type.go:8: Char在此块中重新声明

是否有任何方法可以通过构造函数强制进行type初始化?或者我是否提出了正确的问题?

让我换一种说法:如果用户说var c Char = "abc",他们将得到一个类型Char的无效值 - 是否有任何方法可以强制用户使用func NewChar(string) Char作为Char的唯一有效构造函数?

英文:

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
<pre>
type Char string
</pre>

can use that type with a declaration
<pre>
var c1 Char("abc")
var c2 Char = "abc"
</pre>

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
<pre>
func Char( s string ) Char {
var ch string = s[0]
return ch
}
</pre>

of course having the type Char and func Char is not the way to do it
<pre>
type.go:8: Char redeclared in this block
</pre>

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 = &quot;abc&quot; 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?

答案1

得分: 10

这是char包。请注意未导出的Char结构体字段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)
}

这是如何使用char包的示例。

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', )
}

输出:

z a-z false ก
英文:

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 &amp;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 (
	&quot;char&quot;
	&quot;fmt&quot;
)

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

Output:

z a-z false ก

答案2

得分: 2

在第一步,看下面的例子。

package main

func main() {
    s := "hello 世界"
    //用于从字符串中获取字符

    cells := []int(s)
    for _, c := range cells {
        println(c, string(c))
        // 你将得到
        // 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
    }
}

[]int(s) 的意思是 "转换为 Unicode 字符"。
[]byte(s) 的意思是 "转换为字节"。

而且,Go 语言没有构造函数。按照 Go 的风格,包提供了 NewXXX() 函数来创建 XXX 对象。

type Client struct {
    // ...
}

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

更新:

如果你的意思是将 Char 定义为 "字符串的一个元素",你应该定义如下。

type Char int

或者

type Char byte

你的定义

type Char string

是对 "字符串" 的重新定义。因此它可以存储字符串。

英文:

At the first, see following example.

package main

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

    cells := []int(s)
    for _, c := range cells {
        println(c, string(c))
        // You&#39;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 &amp;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.

答案3

得分: 0

一个Go语言中的单个Unicode字符由一个uint32表示。
你可以这样做:

type Char uint32
var a Char = 'a'

不需要构造函数,因为你可以直接使用字符字面量。

英文:

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

type Char uint32
var a Char = &#39;a&#39;

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

答案4

得分: 0

除了其他答案之外,应该注意到Go语言没有特殊的构造函数语法。不过,有一些约定。通常情况下,当你有一个自定义类型并且需要一个构造函数时,你会编写一个NewT()函数,该函数接受任何你需要的参数,执行初始化操作,并返回一个该类型的实例。

type Char string

func NewChar(s string) Char {
    if len(s) == 0 {
       return Char("")
    }
    return Char(s[: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(&quot;&quot;)
    }
    return Char(s[:1])
}

huangapple
  • 本文由 发表于 2011年6月21日 13:26:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/6420734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定