0

Не могу понять почему у масива отсутствует append метод.

package main

import (
    "fmt"
    "net/http"
    "html/template"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

const db_name = "news"
const db_table = "posts"
const db_login = "database"
const db_password= "xxxxxxxxxxxxxxxxxxxxxxxxx"
const db_host = "xxx.xxx.xxx.xxx"
const db_port = "xxxx"

type Post struct {
    ID          int
    Title       string
    Context     string
    CreatedAt   string
}

type PageData struct {
    PageTitle string
    PageHeader string
    Posts []Post
}

func main() {
    conn, err := sql.Open("mysql", db_login + ":" + db_password + "@tcp(" + db_host + ":" + db_port + ")/" + db_name)
    if err != nil {
        panic(err)
    }

    rows, err := conn.Query("SELECT * FROM " + db_table)
    if err != nil {
        panic(err)
    }

    posts := []Post{}

    for rows.Next() {
        post := new(Post)
        err := rows.Scan(&post.ID, &post.Title, &post.Context, &post.CreatedAt)
        if err != nil {
            panic(err)
        }
        posts.append(posts, &post)
    }

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        data := PageData {
            PageTitle: "News",
            PageHeader: "News",
            Posts: posts,
        }
        tmpl, _ := template.ParseFiles("index.html")
        tmpl.Execute(w, data)
    })
    http.ListenAndServe(":80", nil)
    defer conn.Close()
}

Ошибка:

posts.append undefined (type []Post has no field or method append)  

1 ответ 1

0

Я не знаю, откуда вы это вычитали, но в Go append есть и всегда был функцией:

posts = append(posts, &post)
1
  • Спасибо. Наверное надо поспать))
    – oyaro
    10 дек 2019 в 20:46

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.