An Interest In:
Web News this Week
- May 1, 2024
- April 30, 2024
- April 29, 2024
- April 28, 2024
- April 27, 2024
- April 26, 2024
- April 25, 2024
Learning Go Basics with 30 Days of (Explained) Code - Day 0: Hello, World
Hello, refactored chimps!
This is post[0]
of a series of [30]Post
destined to new Gophers and sympathizers.
In this series, we are going to explore fundamental Go concepts while solving basic algorithm problems. By the end, you should have a general view of Go and be able to understand and write some Go code on your own.
If youre looking for a problem-based approach for beginners, this is the place for you!
Day 0: Hello, World
Today we are going to code the genesis of all algorithms ever written in any language: the classic Hello, World.
But dont mistake yourself! For a simple algorithm as such, we are going to cover:
- Go packages and code structure
- the
fmt
,os
, andbufio
packages from Go's standard library - the 4 declarative forms that Go allows
What is the problem?
The problem consists of outputting to the console both the statement Hello, World.
and an input read from Stdin
.
To complete this challenge, we need to:
- Save a line of input from
Stdin
to a variable - Print
Hello, World.
to the console on a single line - Print the value from step 1 on a second line
For the full problem description, go to HackerRanks Day 0: Hello, World.
What do we need to know about Go?
Go packages and code structure
Go deals with source code using packages. Therefore, every source code file must start with a package declaration. We declare packages by typing the keyword package
followed by the packages name. The packages name must be the same as that of the file. So if we have a package myPackage
, we need to store it inside of the myPackage.go
file.
For every Go application, main
is the pre-defined executable package. Go uses this package to generate an executable that runs our program. The package must be inside of the main.go
file, and it must present a function called main
, which we declare by typing func main()
.
Packages can also be exported and imported to enable code reuse. That means you can write multiple packages and reuse those somewhere else simply by importing them. To import packages, we use the keyword import
.
There are two ways of importing packages: single package or multi-package import. To import a single package, we type import
and the packages name between double quotes.
To import multiple packages at once, we declare the packages inside of parentheses, separated by line breaks.
The package statement, package import, and function declaration form the basic code structure for all Go programs.
The fmt
, os
, and bufio
packages from Go's standard library
Go has a list of supported standard and community Packages. We are going to use three packages from Gos standard library: fmt
, os
, and bufio
.
fmt
and formatting output
The fmt
package provides functions to format input and output. After importing fmt
into our package, we access these functions by typing fmt.FunctionName()
.
Print
, Printf
, and Println
are 3 of the functions that can be used to handle output. Here, we are going to focus only on the formatting differences.
When using fmt.Print()
to output a string
, we need to manually format the output by adding the necessary space and line breaks.
fmt.Printf()
allows us to write the same string
as a straight line by referencing the variables with format specifiers. Format specifiers are operators that identify the type of data stored in a variable. They are represented by a percentage operator and a character that indicates data type. For example, %d
is used for integer
and %s
for string
.
Finally, fmt.Println()
facilitates formatting by adding spaces between operands and a line break by the end of the output. Therefore, we could simply write:
os
, bufio
, and reading standard input
The os
package provides an uniform interface to work with operating system functionality across all operating system platforms. os.Stdin
is the functionality we will use to point to Stdin
when reading input with the bufio
package.
The bufio
package implements buffered input and output functionality. It allows for different ways of reading input, but we will focus on type Scanner
.
Scanner
provides an interface for reading newline-delimited lines of text. To work with it, we provision a Scanner
object, pointing it to Stdin
by using os.Stdin
.
The Scanner.Scan()
function responds with true
or false
to indicate if there is any input available. After finding an input, Scanner.Text()
returns the full input as a string
.
The 4 declarative forms that Go allows
Go supports 4 ways of declaring variables. We already saw 3 of them above, but we are going to cover them all in more detail.
The standard syntax for declaring a variable is the keyword var
followed by the variables name and its type. We can assign a value to the variable anywhere inside the block scope.
If our variable has a well-known initial value, we can initialize it along with its declaration. In this case, we type the assignment =
operator followed by its initial value.
One thing you may have noticed by now is that Go is a strongly, statically typed language. Therefore, we must always indicate the type of the data which will be stored in our variable.
But the Go compiler is capable of inferring data type based on the data that is stored. That means, if we assign a string
to a variable, it will automatically declare that variable as being of string
type. This way, we can omit the data type from the previous declaration.
Theres an even shorter way of declaring variables in Go: the short declaration. It doesnt require the var
keyword nor the data type. We only need to write the variables name followed by the colon equals :=
operator and the initial value.
All the previous declarative forms support multi-variable declarations and assignments, separated by commas.
Now, I believe we know everything we need in order to solve the challenge. Time to get our hands dirty.
Step-by-step coding explained
To start any Go program, we need to declare the package we are working on.
Save a line of input from Stdin
to a variable
The first step towards the solution is attributing the input from Stdin
to a variable. To work with Stdin
, we will need os
functionality. We will also use bufio
to Scan
the input. Therefore, we must import these two packages. For that, we are going to use the multi-package import syntax.
Lets start our code inside of the main
function by instantiating a Scanner
object. In order to read input, we need to point Scanner
to Stdin
while instantiating it.
We also need a variable to store the string
being passed as input. In this case, since there is no initial value, we are going to use the standard syntax.
One new thing to mention is, Gos name convention tells us to use the first letters of the words that best represent the data or role of our variables and functions. Despite using descriptive camelCase
during explanation, well always follow this convention when writing actual code. Thus, well call our input string is
.
Now we can use the Scan()
function to check for input and the Text()
function to store the input in our is
variable.
Print Hello, World.
to the console on a single line
To print something to the console, we need the fmt
package. So lets add it to our import
statement.
After importing fmt
, we are ready to use any of the 3 output functions we saw to print out the Hello, World.
statement. Im using Println()
, but feel free to try another one.
Print the value from step 1 on a second line
The last step is to print out the value we read from Stdin
. This value is stored in our is
variable. Since it's the last output, Im using Print()
this time.
That completes the challenge, the full code as follows:
Key Takeaways
Every Go program starts with a package declaration.
main
is the one and only executable package in a Go program.You can reuse code by exporting and importing packages.
Go supports several standard and community packages.
You can use the
fmt
package to format input and output, including thefmt.Print()
,fmt.Printf()
, andfmt.Println()
output functions.You can use the
bufio
andos
packages to read input by instantiating aScanner
object pointed toStdin
.When using
Scanner
,Scan()
returnstrue
when theres input andText()
returns the input as astring
.Go allows 4 ways to declare variables. All these ways support both single and multiple declaration and attribution.
Gos convention is to name variables or functions by using the first letters of each word that best describes their value or role.
Full commented solution
Resources
Ill answer any follow-up questions in the comments below.
And I hope to see you in the next post.
For now, so long, and thanks for all the gophers.
Please, let me hear from you. Your feedback is essential.
Original Link: https://dev.to/caiomarte/learning-go-basics-with-30-days-of-explained-code-day-0-hello-world-1o57
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To