Golang结构体数组转换

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

golang struct array conversion

问题

我有以下结构体:

type Foo struct{
  A string
  B string
}

type Bar struct{
  C string
  D Baz
}

type Baz struct{
  E string
  F string
}

假设我有一个 []Bar,如何将其转换为 []Foo

A 应该是 C

B 应该是 E

英文:

I have structs like below:

type Foo struct{
  A string
  B string
}

type Bar struct{
  C string
  D Baz
}

type Baz struct{
  E string
  F string
}

Lets say I have []Bar, how to convert this to []Foo ?

A should be C

B should be E

答案1

得分: 5

我不认为有任何“神奇”的方法可以进行转换。然而,创建它只需要很少的代码。像这样的代码应该可以解决问题。

func BarsToFoos(bs []Bar) []Foo {
  var acc []Foo

  for _, b := range bs {
    newFoo := Foo{A: b.C, B: b.D.E}  // 为了清晰起见而提取出来
    acc = append(acc, newFoo)
  }

  return acc
}

这段代码将一个类型为[]Bar的切片转换为一个类型为[]Foo的切片。在循环中,它遍历每个Bar对象,并使用其中的字段值创建一个新的Foo对象,然后将其添加到acc切片中。最后,返回acc切片作为结果。

英文:

I don't think there's any "magic" way of doing the conversion. However, it is a very small piece of coding to create it. Something like this ought to do the trick.

func BarsToFoos(bs []Bar) []Foo {
  var acc []Foo

  for _, b := range bs {
    newFoo := Foo{A: b.C, B: b.D.E}  // pulled out for clarity
    acc = append(acc, newFoo)
  }

  return acc
}

答案2

得分: 2

例如,简洁地最小化内存分配和使用,

package main

import "fmt"

type Foo struct {
	A string
	B string
}

type Bar struct {
	C string
	D Baz
}

type Baz struct {
	E string
	F string
}

func FooFromBar(bs []Bar) []Foo {
	fs := make([]Foo, 0, len(bs))
	for _, b := range bs {
		fs = append(fs, Foo{
			A: b.C,
			B: b.D.E,
		})
	}
	return fs
}

func main() {
	b := []Bar{{C: "C", D: Baz{E: "E", F: "F"}}}
	fmt.Println(b)
	f := FooFromBar(b)
	fmt.Println(f)
}

输出:

[{C {E F}}]
[{C E}]
英文:

For example, concisely mininimizing memory allocations and use,

package main

import "fmt"

type Foo struct {
	A string
	B string
}

type Bar struct {
	C string
	D Baz
}

type Baz struct {
	E string
	F string
}

func FooFromBar(bs []Bar) []Foo {
	fs := make([]Foo, 0, len(bs))
	for _, b := range bs {
		fs = append(fs, Foo{
			A: b.C,
			B: b.D.E,
		})
	}
	return fs
}

func main() {
	b := []Bar{{C: "C", D: Baz{E: "E", F: "F"}}}
	fmt.Println(b)
	f := FooFromBar(b)
	fmt.Println(f)
}

Output:

[{C {E F}}]
[{C E}]

huangapple
  • 本文由 发表于 2015年11月13日 17:30:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/33689553.html
匿名

发表评论

匿名网友

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

确定