Go in Plain English: Creating your First WebServer
In this article I'm going to start with Strings to give you some hands-on exposure.
You need to install Go first and ideally a code editor like VS Code as shown in Golang in Plain English: Settings things up and Hello World!
The way I'll go through variables here is the way I taught myself Go so it shouldn't be hard.
Just repeat what I do here and you should be fine. Here's what I'll go through:
This is how we declare a variable in Go:
Go makes it easier by letting you both declare and set the variable at the same time by adding a colon before the equals sign like this:
However, if I try to run it Go won't let me because it requires that all declared variables must be used:
So if we add a print statement it will work:
Note that %s means we're printing a string. If it was an integer, for example, you'd use %d instead.
It now works:
Let's say you just want to print DevCentral (character 0 to 10) but you don't want to touch the variable.
This is what you do:
Here's the output:
You could've omitted the 0 leaving just my variable[:10] and Go would understand that starting position is 0 anyway.
We can also do the other way round if we want to print just awesome (character 14 until the end).
This time I'm just going to omit the last position as Go understands it's up to the end:
The other MUST know is how to go through each character in a for loop using range:
The first thing to understand here is that our for loop requires 2 things: the index we're at (0,1,2,3, etc) and the character.
So first iteration: i = 0, c = 'D', 2nd iteration: i = 1, c = 'e', and so on.
Let's print this out:
Let's say you don't care about the index.
In that case, Go has something very handy for this.
Just use the _ character and Go will ignore it:
Here we go:
If it's just the index, you don't need the _ because Go already understands that you just want to print the index as it's the first entry (from i,c):
And here's the output again:
Another useful thing is to learn how to print the length of a string which is not very different from other programming languages:
How do we print double quotes inside of print statement?
Just put your string between back quotes like this:
Let's run it:
Oops! It also printed our new line character. Let's fix it by taking it out of our back quotes and merging it between double quotes like this:
Let's run it one more time: