I have just started learning Golang and would like to list months in order for a options in an html select tag:
I have started this:
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
", i, n)
}
}
I would like to print out this:
<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>
For example,
package main
import (
"fmt"
"time"
)
func main() {
for i := time.January; i <= time.December; i++ {
fmt.Printf("<option>%s</option>
", i)
}
}
Output:
<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>
You are nearly there:
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>
", month)
}
}
The only tricky part is to use _
instead of i
, to avoid an error "i declared and not used" when you try to build your program. _
is called the blank identifier, you can learn more in the go documentation.