Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Go Syntax


Go Syntax

A Go file consists of the following parts:

  • Package declaration
  • Import packages
  • Functions
  • Statements and expressions

Look at the following code, to understand it better:

Example

package main
import ("fmt")

func main() {
  fmt.Println("Hello World!")
}
Try it Yourself »

Example explained

Line 1: In Go, every program is part of a package. We define this using the package keyword. In this example, the program belongs to the main package.

Line 2: import ("fmt") lets us import files included in the fmt package.

Line 3: A blank line. Go ignores white space. Having white spaces in code makes it more readable.

Line 4: func main() {} is a function. Any code inside its curly brackets {} will be executed.

Line 5: fmt.Println() is a function made available from the fmt package. It is used to output/print text. In our example it will output "Hello World!".

Note: In Go, any executable code belongs to the main package.


Go Statements

fmt.Println("Hello World!") is a statement.

In Go, statements are separated by ending a line (hitting the Enter key) or by a semicolon ";".

Hitting the Enter key adds ";" to the end of the line implicitly (does not show up in the source code).

The left curly bracket { cannot come at the start of a line.

Run the following code and see what happens:

Example

package main
import ("fmt")

func main()
{
  fmt.Println("Hello World!")
}
Try it Yourself »

Go Compact Code

You can write more compact code, like shown below (this is not recommended because it makes the code more difficult to read):

Example

package main; import ("fmt"); func main() { fmt.Println("Hello World!");}
Try it Yourself »

Go Exercises

Test Yourself With Exercises

Exercise:

Insert the missing part of the code below to output "Hello World".

package main   
import ("fmt")
func main() { ("Hello World!") }

Start the Exercise


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.