how to insert value in first slice index in golang

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

how to insert value in first slice index in golang

问题

我有一个结构体和数组切片。

type Book struct {
	bookName string
	category string
	creator  string
}

var books = []Book{
	{bookName: "study go", category: "programming", creator: "steve"},
	{bookName: "study html", category: "programming", creator: "jobs"},
}

func main() {

//如何将数据添加到索引[0]或books的前面

}
英文:

i have an struct & array slice

type Book struct {
	bookName string
	category string
	creator  string
}

var books = []Book{
	{bookName: "study go", category: "programming", creator: "steve"},
	{bookName: "study html", category: "programming", creator: "jobs"},
}

func main() {

//how to add data to index[0] or front of books

}

答案1

得分: 0

这样怎么样?

package main

import "fmt"

func test() {
    books = append([]Book{{
        bookName: "学习C++",
        category: "编程",
        creator:  "tmp",
    }}, books...)
    fmt.Println(books)
}
英文:

How about this?

package main

import "fmt"

func test() {
	books = append([]Book{{
		bookName: "study c++",
		category: "programing",
		creator:  "tmp",
	}}, books...)
	fmt.Println(books)
}

答案2

得分: -1

你的问题没有明确。我已经尝试给你一个答案。我将books变量中的第一个索引与new变量中的其他数据组合在一起。

package main

import "fmt"

type Book struct {
	bookName string
	category string
	creator  string
}

func main() {
	var books = []Book{
		{bookName: "study go", category: "programming", creator: "steve"},
		{bookName: "study html", category: "programming", creator: "jobs"},
	}
	var new = []Book{
		{bookName: "study css", category: "Styling", creator: "john"},
	}
	new = append(books[0:2], new[0])
	fmt.Println(new)
}

结果

[{study go programming steve} {study html programming jobs} {study css Styling john}]
英文:

Your question is not clarified. I have tried to give you an answer. I combined the first index in the books variable with other data in the new variable.

package main

import "fmt"

type Book struct {
	bookName string
	category string
	creator  string
}

func main() {
	var books = []Book{
		{bookName: "study go", category: "programming", creator: "steve"},
		{bookName: "study html", category: "programming", creator: "jobs"},
	}
	var new = []Book{
		{bookName: "study css", category: "Styling", creator: "john"},
	}
	new = append(books[0:2], new[0])
	fmt.Println(new)
}

Result

[{study go programming steve} {study html programming jobs} {study css Styling john}]

huangapple
  • 本文由 发表于 2021年9月17日 09:03:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/69216663.html
匿名

发表评论

匿名网友

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

确定