dongxi1943 2013-07-13 02:11
浏览 33
已采纳

转到:将基元切片转换为其别名的切片

I'm trying to do something along these lines:

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

Am I doing something wrong? Or is this simply a limitation in go?

  • 写回答

1条回答 默认 最新

  • dpqjvoq9033 2013-07-13 02:53
    关注

    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.

    For example,

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

    Output:

    [a b c]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像