登录
首页 >  Golang >  Go问答

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

来源:SegmentFault

时间:2023-01-10 13:42:25 432浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《《The way to go》代码cars.go 执行不成功》,涉及到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”

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

正确答案

cars = append(cars, c)

测试运行: http://play.golang.org/p/mKzV9ayrba

本篇关于《《The way to go》代码cars.go 执行不成功》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>