This project is inspired by the Golang for Node.js developers project. Similar to that project, I will do my best to provide numerous examples for those who are familiar with Python and are interested in learning Go. Personally, my journey is similar to yours. I started with Python and later became drawn to this delightful and efficient language :)
mutable_variable=2CONST_VARIABLE=3.14# There isn't a way to define a constant variable in Pythona, b=1, "one"# Declaring two mutable variables at oncevarmutableVariableint=2constConstVariablefloat=3.14vara, b=1, "one"// Go automatically assigns types to each variable (type inferred), so you can't change them later.string_var="Hello Python!"integer_var=2float_var=3.14boolean_var=Truevarstring_varstring="Hello Go!"varinteger_varint=2varfloat_varfloat=3.14varboolean_varbool=truei=10foriinrange(10):
print(i)// Initial; condition; after loopfori:=0; i<10; i++ { // Using the shorthand syntax of declaring a variable in Go (mutableVar := the value)fmt.Println(i)
}counter=0whilecounter<5:
print(counter)
counter+=1varcounterint=0forcounter<5 {
fmt.Println(counter)
counter+=1
}age=25ifage>=13andage<=19:
print("Teenager")
elifage>=20andage<=29:
print("Young adult")
elifage>=30andage<=39:
print("Adult")
else:
print("Other")varageint=25ifage>=13&&age<=19 {
fmt.Println("Teenager")
} elseifage>=20&&age<=29 {
fmt.Println("Young adult")
} elseifage>=30&&age<=39 {
fmt.Println("Adult")
} else {
fmt.Println("Other")
}mix_list= [False, 1, "two"] # Can be any sizevarboolArray [3]bool= [3]bool{false, true, true} // var variableName [array size]type of array elementsvarstringArray [3]string= [3]string{"zero", "one", "two"}
varintArray [3]int= [3]int{0, 1, 2}
varboolSlice []bool= []bool{false} // var variableName []type of slice elementsvarstringSlice []string= []string{"zero", "one"}
varintSlice []int= []int{0, 1, 2}mix_list= [False, 1, "two"]
foriteminmix_list:
print(item)varintSlice []int= []int{0, 1, 2}
forindex, value:=rangeintSlice {
fmt.Println(index, value)
}Think of Map as Python's dictionary. Like an Array/Slice, it requires specifying key and value types.
the_dictionary= {"hi": 1, "bye": False}
print(the_dictionary["hi"])vartheMapmap[string]int=map[string]int{"hi": 1, "bye": 0}
fmt.Println(theMap["hi"])defthe_function(first_arg, second_arg):
returnf"The first argument is {first_arg} and the second argument is {second_arg}", TruefunctheFunction(firstArgstring, secondArgstring) (string, bool) { // (argument argumentType) (return typeValue)returnfmt.Sprintf("The first argument is %s and the second argument is %s", firstArg, secondArg), true
}importrequestsresponse=requests.get("https://example.com/")
print(response.content)import (
"fmt""io""log""net/http"
)
resp, err:=http.Get("https://example.com/")
iferr!=nil {
log.Println(err)
}
deferresp.Body.Close()
body, err:=io.ReadAll(resp.Body)
fmt.Println(string(body))