Principal
public class Main { public static void main(String[] args) { Integer a = 127; Integer b = 127; Integer c = 128; Integer d = 128; System.out.println(a == b); System.out.println(c == d); } } package main import "fmt" func main() { x := 1 defer func() { fmt.Println("defer:", x) }() x = 2 fmt.Println("now:", x) }
sobes.tech AI
Odpowiedź od AI
W Java:
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b); // true
System.out.println(c == d); // false
Wyjaśnienie:
Java buforuje obiekty Integer w zakresie od -128 do 127. Dlatego a i b odwołują się do tego samego obiektu, a porównanie == zwraca true. Dla wartości spoza tego zakresu tworzone są nowe obiekty, więc c == d jest false.
W Go:
package main
import "fmt"
func main() {
x := 1
defer func() { fmt.Println("defer:", x) }()
x = 2
fmt.Println("teraz:", x)
}
Wyjście będzie:
teraz: 2
defer: 2
Wyjaśnienie:
W Go funkcje odłożone za pomocą defer przechwytują zmienne przez referencję, a nie przez wartość. Dlatego podczas wykonywania opóźnionej funkcji wartość x jest już równa 2.