Answer the question
In order to leave comments, you need to log in
The function does not accept or return a structure?
Hello. Briefly: the MainPage function processes the main page and also unloads the table from the database into a slice of structures.
Next From this slice of structures, a random object is taken, assigned to the show variable, which is passed to the page to display data from the database.
type WordsStruct struct {
Id int
Fword string
Sword string
Freq int
}
func MainPage(w http.ResponseWriter, r *http.Request) {
m, _ := template.ParseFiles("html/main.html", "html/header.html", "html/footer.html")
res, err := database.Query(fmt.Sprintf("SELECT * FROM `words`"))
if err != nil {
panic(err)
}
defer res.Close()
showarray := []WordsStruct{}
for res.Next() {
var sw WordsStruct
err := res.Scan(&sw.Id, &sw.Fword, &sw.Sword, &sw.Freq)
if err != nil {
fmt.Println(err)
continue
}
showarray = append(showarray, sw)
}
rand.Seed(time.Now().Unix())
show := showarray[rand.Intn(len(showarray))]
//w.Header().Set("Content-Type", "text/html")
m.ExecuteTemplate(w, "main", show)
}
rand.Seed(time.Now().Unix())
show := showarray[rand.Intn(len(showarray))]
show := Next(showarray)
// ***
func Next(st []struct{}) struct{} {
rand.Seed(time.Now().Unix())
shw := st[rand.Intn(len(st))]
return shw
}
Answer the question
In order to leave comments, you need to log in
To be honest, I didn’t quite understand why in the code you show that you are passing st []struct{} and returning struct{}, you need to specify a specific data type. Here is the working code
package main
import (
"fmt"
"math/rand"
"time"
)
type WordsStruct struct {
Id int
Fword string
Sword string
Freq int
}
func Next(st []WordsStruct) WordsStruct {
rand.Seed(time.Now().Unix())
shw := st[rand.Intn(len(st))]
return shw
}
func main(){
st := []WordsStruct{
{Id: 1, Fword: "test", Sword:"est" , Freq:5 },
{Id: 2, Fword: "rest", Sword:"ww" , Freq:75 },
}
fmt.Println(Next(st))
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question