-2

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

}
mkopriva
  • 35,176
  • 4
  • 57
  • 71
  • 3
    Does this answer your question? [Insert a value in a slice at a given index](https://stackoverflow.com/questions/46128016/insert-a-value-in-a-slice-at-a-given-index) – Trock Sep 17 '21 at 01:07

2 Answers2

0

How about this?

package main

import "fmt"

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

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}]
Bilal Khan
  • 119
  • 1
  • 9
  • why {bookName: "study html", category: "programming", creator: "jobs"} deleted? i want result to [ {study css Styling john}{study go programming steve}{study html programming steve}] – ryandi pratama purba Sep 17 '21 at 03:36
  • @ryandipratamapurba You said that you just want index[0] that is the first one. Now I updated the code including all of them. – Bilal Khan Sep 17 '21 at 05:24