Sobes.tech
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

Odpoveď od AI

V Jave:

Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;

System.out.println(a == b); // true
System.out.println(c == d); // false

Vysvetlenie: Java cacheuje objekty Integer v rozsahu od -128 do 127. Preto a a b odkazujú na ten istý objekt a porovnanie == vracia true. Pre hodnoty mimo tohto rozsahu sa vytvárajú nové objekty, takže c == d je false.

V Go:

package main

import "fmt"

func main() {
    x := 1
    defer func() { fmt.Println("defer:", x) }()
    x = 2
    fmt.Println("teraz:", x)
}

Výstup bude:

teraz: 2
defer: 2

Vysvetlenie: V Go, funkcie odložené pomocou defer zachytávajú premenné odkazom, nie hodnotou. Preto pri vykonaní odloženej funkcie je hodnota x už 2.