在Go语言中,将字符串类型的数组转换为字符串数组的最佳方法是什么?

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

In Go what is the best way to convert an array of string types to an array of string

问题

以下是代码的翻译:

package main

import "strings"
import "fmt"

type Foo string

const (
    Bar    Foo = "bar"
    Snafu      = "snafu"
    Foobar     = "foobar"
)

var Foos = []Foo{Bar, Snafu, Foobar}

func main() {
    fmt.Println("Foos: " + strings.Join(Foos, ","))
}

产生了以下错误:

./test.go:17: cannot use Foos (type []Foo) as type []string in argument to strings.Join

这是有道理的,因为Foo不是string类型,但它是从string派生出来的。有没有办法在不复制的情况下将[]Foo强制转换为[]string呢?

英文:

The following code

package main

import "strings"
import "fmt"

type Foo string

const (
	Bar    Foo = "bar"
	Snafu      = "snafu"
	Foobar     = "foobar"
)

var Foos = []Foo{Bar, Snafu, Foobar}

func main() {
	fmt.Println("Foos: " + strings.Join(Foos, ","))
}

Produces this error:

./test.go:17: cannot use Foos (type []Foo) as type []string in argument to strings.Join

This makes sense since Foo is not string but it is derived from string. Is there any way to coerce the "[]Foo" to "[]string" without copying?

答案1

得分: 5

基本上,最好且唯一的方法是循环遍历 Foo 对象的切片(导致复制):

func main() {
    results := make([]string, 0, len(Foos))
    for _, r := range Foos{
       results = append(results, string(r))
    }
    fmt.Println("Foos: " + strings.Join(results, ","))
}

不幸的是,截至目前,Go 不支持类型强制转换的概念,需要进行复制。作为替代方案,您可以为 []Foo 类型创建类型别名,并添加一个 Stringer 方法来封装这些细节,如下所示:链接

请参考以下类似问题的链接:链接

英文:

Pretty much the best and only way to do it is to loop over the slice of Foo objects as in (causing a copy):

func main() {
    results := make([]string, 0, len(Foos))
    for _, r := range Foos{
       results = append(results, string(r))
    }
    fmt.Println("Foos: " + strings.Join(results, ","))
}

Unfortunately as of this time Go does not support the concept type coercion and requires a copy. As an alternative you can type alias []Foo and add a Stringer method to it therefore encapsulating such details as in: http://play.golang.org/p/FuOoLNrCvD

See the following for a similar question: https://stackoverflow.com/questions/12990338/cannot-convert-string-to-interface

答案2

得分: 0

你可以使用我创建的https://github.com/ledongthuc/goterators#map来重用聚合和转换函数。

package main

import (
	"fmt"
	"strings"

	"github.com/ledongthuc/goterators"
)

type Foo string

const (
	Bar    Foo = "bar"
	Snafu      = "snafu"
	Foobar     = "foobar"
)

var Foos = []Foo{Bar, Snafu, Foobar}

func main() {
	strs := goterators.Map(Foos, func(item Foo) string {
		return string(item)
	})
	fmt.Println("Foos: " + strings.Join(strs, ","))
}

或者,如果你想要一种优化的方式,你可以使用Reduce。

package main

import (
	"fmt"

	"github.com/ledongthuc/goterators"
)

type Foo string

const (
	Bar    Foo = "bar"
	Snafu      = "snafu"
	Foobar     = "foobar"
)

var Foos = []Foo{Bar, Snafu, Foobar}

func main() {
	joinStr := goterators.Reduce(Foos, "", func(previous string, current Foo, index int, list []Foo) string {
		if len(previous) == 0 {
			return string(current)
		}
		return previous + "," + string(current)
	})
	fmt.Println("Foos: " + joinStr)
}

它们需要使用go 1.18来支持你想要使用的通用+动态类型。

英文:

You can use https://github.com/ledongthuc/goterators#map that I created to reuse aggregate & transforms functions.

在Go语言中,将字符串类型的数组转换为字符串数组的最佳方法是什么?

package main

import (
	"fmt"
	"strings"

	"github.com/ledongthuc/goterators"
)

type Foo string

const (
	Bar    Foo = "bar"
	Snafu      = "snafu"
	Foobar     = "foobar"
)

var Foos = []Foo{Bar, Snafu, Foobar}

func main() {
	strs := goterators.Map(Foos, func(item Foo) string {
		return string(item)
	})
	fmt.Println("Foos: " + strings.Join(strs, ","))
}

Or if you want an optimized way, you can use Reduce

在Go语言中,将字符串类型的数组转换为字符串数组的最佳方法是什么?

package main

import (
	"fmt"

	"github.com/ledongthuc/goterators"
)

type Foo string

const (
	Bar    Foo = "bar"
	Snafu      = "snafu"
	Foobar     = "foobar"
)

var Foos = []Foo{Bar, Snafu, Foobar}

func main() {
	joinStr := goterators.Reduce(Foos, "", func(previous string, current Foo, index int, list []Foo) string {
		if len(previous) == 0 {
			return string(current)
		}
		return previous + "," + string(current)
	})
	fmt.Println("Foos: " + joinStr)
}

They are required go 1.18 to use that support generic + dynamic type you want to use with.

huangapple
  • 本文由 发表于 2015年1月20日 01:36:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/28030469.html
匿名

发表评论

匿名网友

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

确定