为什么我的Slice in Go无法保存数据?[已关闭]

3qpi33ja  于 2023-01-10  发布在  Go
关注(0)|答案(1)|浏览(168)

**已关闭。**此问题为not reproducible or was caused by typos。当前不接受答案。

这个问题是由打字错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
2天前关闭。
Improve this question
我正在学习围棋。当我试图在切片中添加一个名字时,它并不包含以前的名字。有人能告诉我出了什么问题吗?(以下是代码)

package main

import "fmt"

func main() {

    eventName := "Go Event"
    const totalTicket uint = 50
    var remainingTicket uint = 50
    fmt.Printf("Welcome to our %v booking app!\n", eventName)
    fmt.Print("Get your tickets now!\n")

    for {
        var bookings []string

        var userName string
        var userTickets uint

        fmt.Println("Enter your name")
        fmt.Scan(&userName)
        

        fmt.Println("Enter the amount of tickets you want to purchase")
        fmt.Scan(&userTickets)

        bookings = append(bookings, userName)
        remainingTicket = remainingTicket - userTickets
        fmt.Printf("All the bookings: %v\n", bookings)
        fmt.Printf("User %v booked %v tickets\n", userName, userTickets)
        fmt.Printf("Remaining Tickets: %v\n", remainingTicket)
    }
}

roejwanj

roejwanj1#

for {
    var bookings []string

切片“bookings”将为每个循环迭代重新声明。这就是为什么每个新的append条目都在第一个,因为重新声明对象将分配一个新的内存地址来保存数据。将此语句移到for循环声明之前将解决此问题。

package main

import "fmt"

func main() {

    eventName := "Go Event"
    const totalTicket uint = 50
    var remainingTicket uint = 50
    fmt.Printf("Welcome to our %v booking app!\n", eventName)
    fmt.Print("Get your tickets now!\n")

    var bookings []string

    for {

        var userName string
        var userTickets uint

        fmt.Println("Enter your name")
        fmt.Scan(&userName)
        

        fmt.Println("Enter the amount of tickets you want to purchase")
        fmt.Scan(&userTickets)

        bookings = append(bookings, userName)
        remainingTicket = remainingTicket - userTickets
        fmt.Printf("All the bookings: %v\n", bookings)
        fmt.Printf("User %v booked %v tickets\n", userName, userTickets)
        fmt.Printf("Remaining Tickets: %v\n", remainingTicket)
    }
}

相关问题