Data Structures
Arrays
Java
String cars[] = new String[5] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" };
System.out.println(cars[0]); // Toyota
GoLang
cars := [5]string{"Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda"}
fmt.Println(cars[0]) // Toyota
For-each over an array
Java
for (String car : cars) {
System.out.println(strTemp);
}
GoLang
for _, car := range cars {
fmt.Println("My car is: ", car)
}
Multidimensional array
Java
String langs[][] = new String[][]{{"C#", "C", "Python"},
{"Java", "Scala", "Perl"},
{"C++", "Go", "HTML"}};
GoLang
langs := [3][3]string{{"C#", "C", "Python"},
{"Java", "Scala", "Perl"},
{"C++", "Go", "HTML"}}
For-each over a multi-dimensional array
Java
for (String[] arr : langs) {
for (String lang : arr) {
System.out.println(lang + " ");
}
System.out.println();
}
// C# C Python
// Java Scala Perl
// C++ Go HTML
GoLang
for _, v := range langs {
for _, lang := range v {
fmt.Print(lang, " ")
}
fmt.Println()
}
// C# C Python
// Java Scala Perl
// C++ Go HTML
List/slice
Java
List<String> letters = List.of("a", "b", "c", "d");
letters.add("e");
int length = letters.size();
GoLang
letters := []string{"a", "b", "c", "d"}
letters = append(letters, "e")
length := len(letters)
For-each over a list/slice
Java
letters.forEach(value => System.out.println(value));
GoLang
for _, letter := range letters {
fmt.Println(letter)
}
Maps
Java
Map<String, String> mapA = Map.of("key1", "element1");
mapA.put("key2", "element2");
mapA.remove("key2")
if (mapA.contains("key1")) {
System.out.println(mapA.get("key1")); // element2
}
GoLang
mapA := map[string]string{"key1":"element1"}
mapA["key2"] = "element2"
delete(mapA, "key2")
if value, ok = mapA["key1"]; ok == true {
mapA["key1"] // element2
}
For-each over a map
Java
mapA.forEach((key, value) -> System.out.println(k + ":" + v));
GoLang
for key, value := range mapA {
fmt.Println(key + ":" + value)
}