Java vs Golang: basic syntax

Posted by agent47 on Sun, 23 Jan 2022 04:27:10 +0100

Coding specification

Code layout

1. Curly bracket wrap style

In Java, each statement is marked with a semicolon " Separation, whether to wrap or not does not affect the correctness of the code.

In python, semicolon separation is eliminated, and the effect of parentheses on code logic is also eliminated (various parentheses in python are used for different data types). Therefore, a strict indentation rule is adopted to control the code specification.

Golang cancels semicolon separation in Java and uses newline to divide statements, but retains the use of parentheses.

However, Golang uses curly braces strictly.

In Java, the following two writing methods are correct

public String getString(Integer num) {
    return num.toString();
}

public String getString(Integer num) 
{
    return num.toString();
} 

Only one format is allowed in Golang:

func getString(num int) string {
	return strconv.Itoa(num)
} 

2. Useless variable declaration

In Java, variables can be declared and can not be used.

The variables declared in Golang must be used, otherwise they need to be used_ To replace the variable name, indicating that the variable will not be used:

func getString(num int) string {
	var temp = num // Cannot compile without user
	var _ = num // Normal compilation
	return strconv.Itoa(num)
} 

3. Visible domain rules

Java's visible domain rules for methods, variables and classes are controlled by private, protected and public keywords.

There is only one way to control the visible field in Golang. When the field starts with uppercase, it means that it is visible to the outside, and when it is lowercase, it is only visible to the members in the package.

Golang

  • entity
package entity

type Person struct {
	Name string
	Age int
	id string
}

type student struct {
	detail Person
}

func test() {
	// Visible in this package
	person := &student{detail: Person{
		Name: "Jrobin",
		Age:  24,
		id:   "001",
	}}
	fmt.Println(person)
}
  • main
package main

import (
	"fmt"
	entity "entity"
)

func main() {
	// The id field is not visible
	person := &entity.Person{
		Name: "Jrobin",
		Age:  24,
	}
	fmt.Println(person)
}

Java

  • Person
 public class Person {

    public String name;
    public int age;
    private String id;

    private class Student{
        Person detail;
    }
    public void test(){
        //Visible in this package
        Student student=new Student();
        student.detail.name="Jrobin";
        student.detail.age=24;
        student.detail.id="001";

        System.out.println(toString());
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", id='" + id + '\'' +
                '}';
    }
}

  • main
 public class Main {

    public static void main(String[] args) {

        //The student class is not visible
        Person person=new Person();
        person.name="Jrobin";
        person.age=24;
        //The id field is not visible
    }
}

The Java code here is only designed to compare with the Golang code as much as possible. The actual structure of Golang does not completely correspond to the Java class.

Variable declaration and initialization

Variable declaration syntax

  • Java
    // Object: type to declare, v: variable name, new Object() variable initialization
    Object v = new Object(); 
    int v1;
    String v2;
    int[] v3=new int[10];
    int[] v4=new int[]{0,1,2};
    Map<String,Integer> v5=new HashMap<>();//map, key is of string type, and value is of int type
    private int v6(int a){return 0;}
    int v7,v8;

  • Golang
    // var: variable definition, v1: variable name, int: variable type
    var v1 int
	var v2 string
	var v3 [10]int  // array
	var v4 []int // Array slice
	var v5 struct {
		f int
	}
	var v6 *int // Pointer
	var v7 map[string]int  // map, key is of string type, and value is of int type
	var v8 func(a int) int
	var v9,v10 int //Both v9 and v10 are declared as int

You can also use: = auto inferred variable type:

	var v1 int = 10 // Correct usage 1
	var v2 = 10  // Using mode 2 correctly, the compiler can automatically deduce the type of v2
	v3 := 10  // Using mode 3 correctly, the compiler can automatically deduce the type of v3 

Value type and reference type

The type system of Golang is similar to that of Java, but it should be noted that arrays in Java are reference types, while arrays in Golang are value types. When passing arrays to methods, Java can directly modify the internal values of the original array through the passed in array (shallow copy), but Golang will completely copy a copy to modify (deep copy):

  • Java
    public static void main(String[] args) {
        int[] array = {1, 2, 3};
        change(array);
        System.out.println(Arrays.toString(array)); // -1,2,3
    }

    private static void change(int[] array) {
        array[0] = -1;
    }

  • Golang
func main() {
	array := [...]int{1, 2, 3}
	change(array)
	fmt.Println(array) // 1,2,3
}

func change(array [3]int) {
	array[0] = -1
} 

In Golang, only slice, pointer, channel, map and func belong to reference types, that is, when passing parameters, their pointers are copied in essence, and internal modifications will directly affect the external:

func main() {
	slice := []int{1, 2, 3}
	changeSlice(slice)
	fmt.Println(slice) // -1,2,3

	mapper := map[string]int {
		"num": 0,
	}
	changeMap(mapper)
	fmt.Println(mapper) // num = -1

	array := [...]int{1, 2, 3}
	changePointer(&array)
	fmt.Println(array) // -1,2,3

	intChan := make(chan int, 1)
	intChan <- 1
	changeChannel(intChan)
	fmt.Println(<- intChan) // -1
}

func changeChannel(intChan chan int) {
	<- intChan
	intChan <- -1
}

func changePointer(array *[3]int) {
	array[0] = -1
}

func changeMap(mapper map[string]int) {
	mapper["num"] = -1
}

func changeSlice(array []int) {
	array[0] = -1
}

Topics: Java Go pointer compiler