鸭子在Go上打字 [英] Duck typing in Go

查看:148
本文介绍了鸭子在Go上打字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个 Join 函数,它可以用一个 String()方法取任意对象:

  package main 

import(
fmt
strings


类型myint int

func(i myint)String()string {
return fmt.Sprintf(%d,i)
}

func main(){
parts:= [] myint {myint(1),myint(5),myint(6)}
fmt.Println (parts,,))
}

func Join(parts [] fmt.Stringer,sep string)string {
stringParts:= make([] string,len (parts))
for i,part:= range(parts){
stringParts [i] = part.String()
}
返回strings.Join(stringParts,sep )
}

http://play.golang.org/p/EhkbyibzHw



[] myint 不能传递给加入,因为它不是类型 fmt.Stringer ,所以我有t o write:

  parts:= [] fmt.Stringer {myint(1),myint(5),myint(6) } 

但是如果我需要 parts 另一个值必须是整数的操作?我是否应该将 myint 分割成 Stringer 的片段,然后?


问:我应该将 myint 分割成一片 Stringer 然后?


在Go-Only转换中没有强制转换。但是,从一个具体的非接口类型切片转换为一个接口类型切片是不可能的,除非在循环中明确地进行。原因是,例如你的情况, [] myint backing数组的内存布局与 [] fmt.Stringer 有。 (相关常见问题解答

在附注中,您不必写:

 部分:= [] myint {myint(1),myint (5),myint(6)} 

这应该是一样的:

 部分:= [] myint {1,5,6} 


I want to write a Join function that takes arbitrary objects with a String() method:

package main

import (
    "fmt"
    "strings"
)

type myint int

func (i myint) String() string {
    return fmt.Sprintf("%d", i)
}

func main() {
    parts := []myint{myint(1), myint(5), myint(6)}
    fmt.Println(Join(parts, ", "))
}

func Join(parts []fmt.Stringer, sep string) string {
    stringParts := make([]string, len(parts))
    for i, part := range(parts) {
        stringParts [i] = part.String()
    }
    return strings.Join(stringParts , sep)
}

http://play.golang.org/p/EhkbyibzHw

[]myint cannot be passed to Join, because it is not of type fmt.Stringer, so I have to write:

parts := []fmt.Stringer{myint(1), myint(5), myint(6)}

But what if I need parts for another operation where the values have to be ints? Should I cast a slice of myint to a slice of Stringer then?

解决方案

Q: Should I cast a slice of myint to a slice of Stringer then?

There are no casts in Go - only conversions. But conversion from a slice of concrete, non interface type to a slice of interface type is not possible, except by doing it explicitly in a loop. The reason is that, as for example in your case, the []myint backing array has a different memory layout than []fmt.Stringer has. (Related FAQ)

On a side note, you don't have to write:

parts := []myint{myint(1), myint(5), myint(6)}

This should work identically:

parts := []myint{1, 5, 6}

这篇关于鸭子在Go上打字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆