fmt.Printf/Println does not work outside of a block

Hi,

I tried printing the following:

package main

import "fmt"

var i int = 20 
fmt.Println(i)

func main() {
	var i int = 10
	fmt.Printf("i Value: %d\ti address: %p\n", i, &i)
}

I get an error stating the following:

main.go|6 col 1| : expected declaration, found fmt
main.go|10 col 2| : expected declaration, found fmt

I am trying to print the value and address of the variable i
While I know that the i in the main is different than the i in the main, printing it out is something that’s not working. If the i in the main is commented, then it works well.
What am I missing? Is fmt.Println or fmt.Printf not designed to work outside of a block? Or am I missing something fundamental ?

The only sentences allowed outside a function block are declarations of variables, definition of types and constants

Hi Yamil,
Thanks for the update. How did you get so much knowledge? Did you go through any specific book or online course? Or just practice and experience?

Well, that’s how most compiled languages work. Also you can read this from the language specification if you are used to BNF in general.

https://golang.org/ref/spec

Well, The best way to learn a new language is to write code and see the code of other colleagues… :slight_smile:
And do not forget to reads the docs:ok_hand:

Hi,
I had done some C programming but don’t remember much. But thanks for pointing this out.

That’s a good starting…