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


I tried printing the following:

package main

import "fmt"

var i int = 20 

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 ?

1 Like

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?

1 Like

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.


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:


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

1 Like

That’s a good starting…

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.