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

(Pritesh Ugrankar) #1


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 ?

(Yamil Bracho) #2

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

(Pritesh Ugrankar) #3

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?

(Norbert Melzer) #4

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.

(Yamil Bracho) #5

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:

(Pritesh Ugrankar) #6

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

(Yamil Bracho) #7

That’s a good starting…

(system) closed #8

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