英文:
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}]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论