casting - Go:将基元 slice 转换为其别名的 slice

标签 casting go alias

我正在尝试按照以下方式做一些事情:

package main                                                                                                                                                                                                                                   

import (          
    "fmt"         
)                 

type StringWrap string

func main() {     
    s := []string{"a","b","c"}
    sw := []StringWrap(s) //ERROR: cannot convert s (type []string) to type []StringWrap
    fmt.Println(sw)
}

我做错了什么吗?或者这只是 go 的一个限制?

最佳答案

The Go Programming Language Specification

Types

A type determines the set of values and operations specific to values of that type. A type may be specified by a (possibly qualified) type name or a type literal, which composes a new type from previously declared types.

Type      = TypeName | TypeLit | "(" Type ")" .
TypeName  = identifier | QualifiedIdent .
TypeLit   = ArrayType | StructType | PointerType | FunctionType |
            InterfaceType | SliceType | MapType | ChannelType .

Named instances of the boolean, numeric, and string types are predeclared. Composite types—array, struct, pointer, function, interface, slice, map, and channel types—may be constructed using type literals.

Each type T has an underlying type: If T is a predeclared type or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.

   type T1 string
   type T2 T1
   type T3 []T1
   type T4 T3

The underlying type of string, T1, and T2 is string. The underlying type of []T1, T3, and T4 is []T1.

Conversions

Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.

A non-constant value x can be converted to type T in the case: x's type and T have identical underlying types.

例如,

package main

import "fmt"

type StringSliceWrap []string

func main() {
    s := []string{"a", "b", "c"}
    ssw := StringSliceWrap(s)
    fmt.Println(ssw)
}

输出:

[a b c]

关于casting - Go:将基元 slice 转换为其别名的 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17626331/

相关文章:

C# 工厂 - upcast 是必须的吗?

c++ - 带有多个参数的 static_cast 是怎么回事?

c# - 通用小数不能从 double 转换

.net - 类型转换和解析的区别

go - Windows XP SP3 上的 Accept() 超时设置

go - 在 golang 的大型 ip/子网列表中搜索 ip 的最快方法?

go - 安全地从无 channel 的goroutines中读取共享数据结构

linux - 创建一个以 PWD 作为变量的别名

perl - 难以将 Perl 脚本作为 Bash 别名运行

perl - 使用 perl 单线器的 Csh 别名在创建别名时评估,而不是在使用别名时评估