dtdvlazd56637 2016-08-03 00:12
浏览 29
已采纳

如何使返回变量在函数外不不确定

I'm new to Go and trying to make some proof of concept. As such, I would like to pass my template file names to the template.ParseFiles, like this:

var Templates = template.Must(template.ParseFiles("views/edit.html", "views/view.html", "views/main.html"))

To do it dynamically I'm trying to do:

func ExtractFileNames () (templateFileNames []string) {
    files, _ := ioutil.ReadDir("./views")
    for _, f := range files {
        if strings.Contains(f.Name(), ".html") {   
           templateFileNames=append(templateFileNames, "views/" + f.Name())
        }
    }
    return templateFileNames
}

var Templates = template.Must(template.ParseFiles(templateFileNames))

The function is working OK except that I'm getting an error:

undefined: templateFileNames

This is making think that maybe I'm not using the best approach to this problem.

  • 写回答

1条回答 默认 最新

  • douxi4287 2016-08-03 00:16
    关注

    Return variables –just like normal parameters and method receivers– are scoped to the function body.

    Mentioned in the spec: Declarations and Scope:

    The scope of an identifier denoting a method receiver, function parameter, or result variable is the function body.

    Outside the function they are not in scope, you can't refer to them.

    In your case the very simple fix is that you have to call the function, and what it returns, you can use it (you can pass it along, assign it to a variable etc.):

    var Templates = template.Must(template.ParseFiles(ExtractFileNames()...))
    

    One thing to note here is the ... called the ellipsis. It is required because ExtractFileNames() returns a slice, but template.ParseFiles() has a variadic parameter:

    func ParseFiles(filenames ...string) (*Template, error)
    

    So that ... will tell the compiler that you want to pass the slice "exploded", as the value for the variadic parameter (and not for example a single element in the variadic list...). More on this in the spec: Passing arguments to ... parameters

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)