The following works as a function to open a file
func openFile(filename string) {
var file *os.File
var err error
if file, err = os.Open(filename); err != nil {
log.Printf("Failed to open the file: %s.", filename)
return
}
defer file.Close()
// blahblahblah
}
however, this does not work, when I try to use := to declare the variable file
func updateFrequencies(filename string, frequencyForWord map[string]int) {
if file, err := os.Open(filename); err != nil {
....
}
}
error: ./word_frequencies_2.go:30: undefined: file
But if I changed this slightly, this works
file, err := os.Open(filename)
if err != nil {
log.Printf("Failed to open the file: %s.", filename)
return
}
why can't I use := as part of the if statement?