《The way to go》代码cars.go 执行不成功

package main

import (
    "fmt"
)

type Any interface{}

type Car struct {
    Model       string
    Manufacture string
    BuileYear   int
}

type Cars []*Car

func (cs Cars) Process(f func(car *Car)) {
    for _, car := range cs {
        f(car)
    }
}

func (cs Cars) FindAll(f func(car *Car) bool) Cars {
    cars := make([]*Car, 0)
    cs.Process(func(c *Car) {
        if f(c) {
            append(cars, c)
        }
    })
    return cars
}

func (cs Cars) Map(f func(car *Car) Any) []Any {
    result := make([]Any, 0)
    ix := 0
    cs.Process(func(c *Car) {
        result[ix] = f(c)
        ix++
    })
    return result
}

func MakeSortedAppender(manufacture []string) (func(car *Car), map[string]Cars) {
    sortedCars := make(map[string]Cars)

    for _, m := range manufacture {
        sortedCars[m] = make([]*Car, 0)
    }

    sortedCars["Default"] = make([]*Car, 0)

    appender := func(c *Car) {
        if _, ok := sortedCars[c.Manufacture]; ok {
            sortedCars[c.Manufacture] = append(sortedCars[c.Manufacture], c)
        } else {
            sortedCars["Default"] = append(sortedCars["Default"], c)
        }
    }

    return appender, sortedCars
}

func main() {
    ford := &Car{"Fiesta", "Ford", 2008}
    bmw := &Car{"XL 450", "BMW", 2011}
    merc := &Car{"D600", "Mercedes", 2009}
    bmw2 := &Car{"X 800", "BMW", 2008}

    allCars := Cars([]*Car{ford, bmw, merc, bmw2})
    allNewBMWs := allCars.FindAll(func(car *Car) bool {
        return (car.Manufacture == "BMW") && (car.BuileYear > 2010)
    })
    fmt.Println("All Cars: ", allCars)
    fmt.Println("New BMWs: ", allNewBMWs)

    manufactures := []string{"Ford", "Aston Martin", "Land Rover", "BMW", "Jaugar"}
    sortedAppender, sortedCars := MakeSortedAppender(manufactures)
    allCars.Process(sortedAppender)
    fmt.Println("Map sortedCars: ", sortedCars)
    BMWCount := len(sortedCars["BMW"])
    fmt.Println("We have ", BMWCount, "BMWs")
}

执行就报错 “.\cars.go:27: append(cars, c) evaluated but not used”

看了很久都没看出什么原因,有怀疑过时闭包导致函数访问不了的问题,请帮忙看看是什么情况,谢谢!

阅读 10.2k
2 个回答
新手上路,请多包涵

你应该写成 cars = append(cars, c)
这样就好了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏