2016-08-03 51 views
2

我是新来的Go并尝试做一些概念验证。因此,我想我的模板文件名传递给template.ParseFiles,就像这样:如何使一个返回变量不在函数外部不确定

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

要做到这一点动态我想要做的事:

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)) 

功能除了工作确定我发现了一个错误:

undefined: templateFileNames 

这是使想,也许我没有使用到这个问题的最好办法。

回答

4

返回变量 - 就像常规参数和方法接收器 - 被限定在函数体中。

在规格中提到:Declarations and Scope:

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

他们不是在范围之外的功能,你不能指代他们。

在你的情况很简单的解决方法是,你必须要调用的函数,以及它返回时,你可以用它(你可以把它传递,它分配给一个变量等):

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

这里需要注意的一点是...称为省略号。这是必需的,因为ExtractFileNames()返回片,但template.ParseFiles()有一个可变参数的参数:

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

这样...会告诉你想通过切片“爆炸”的编译器,作为一个可变参数的值(和例如可变参数列表中没有单个元素......)。更多关于这个规格:Passing arguments to ... parameters

+0

是的。我改变了标题,让我的问题更清晰:如何让它在室外工作。谢谢! –

+0

@PauloJaneiro查看编辑答案:只需调用函数,所以它会返回值。 – icza

+0

100%现在在这两个问题上都清楚了!非常感谢。 –

相关问题