Golang Construct月份用于html选择标记中的选项

时间:2014-02-09 04:47:50

标签: go

我刚刚开始学习Golang,并希望列出几个月以便在html选择标记中添加选项:

我已经开始了:

package main

import (
    "fmt"
)

var months = [12]string{
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December",
}

func main(){
    for i, n := range months {
        fmt.Printf("%2d: %s\n", i, n)
    }
}

我想打印出来:

<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>

2 个答案:

答案 0 :(得分:3)

例如,

package main

import (
    "fmt"
    "time"
)

func main() {
    for i := time.January; i <= time.December; i++ {
        fmt.Printf("<option>%s</option>\n", i)
    }
}

输出:

<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>

答案 1 :(得分:0)

你快到了:

package main

import (
    "fmt"
)

var months = [12]string{
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December",
}

func main() {
    for _, month := range months {
        fmt.Printf("<option>%s</option>\n", month)
    }
}

唯一棘手的部分是使用_而不是i,以避免在您尝试构建程序时出现错误“我声明并且未使用”。 _被称为空白标识符,您可以了解更多in the go documentation