Hàm
Destructuring
Destructuring object trong Node.js so với pattern destructuring struct trong Rust, tuple trong Swift, record pattern trong Java và gán nhiều biến trong Go.
- Phiên bản tối thiểu
- Node.js ≥ 12.20Go ≥ 1.0Rust ≥ 1.58Swift ≥ 2.0Java ≥ 25
- Đã chạy thử trên
- Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1
Code Node.js là ES module: lưu file .mjs hoặc đặt "type": "module" trong package.json.
Node.js destructure trực tiếp một object thành nhiều biến bằng cú pháp { key, value } = obj. Rust có cú pháp destructuring struct thật sự qua pattern matching (let Obj { key, value } = obj) — gần với JS nhất. Swift không destructure struct trực tiếp theo tên trường, nhưng destructure tuple thì có (let (key, value) = (...)). Java từ bản 21 có record pattern, destructure được record ngay trong instanceof. Go không có cú pháp destructuring cho struct, nhưng đạt cùng hiệu quả bằng gán nhiều biến cùng lúc hoặc bằng hàm trả về nhiều giá trị.
Lấy nhiều giá trị từ một object
const obj = { key: 'foo', value: 'bar' };
const { key, value } = obj;
console.log(key, value); // foo barpackage main
import "fmt"
type Obj struct {
Key string
Value string
}
func (o *Obj) Read() (string, string) {
return o.Key, o.Value
}
func main() {
obj := Obj{
Key: "foo",
Value: "bar",
}
// cách 1: gán nhiều biến cùng lúc
key, value := obj.Key, obj.Value
fmt.Println(key, value) // foo bar
// cách 2: hàm trả về nhiều giá trị
key, value = obj.Read()
fmt.Println(key, value) // foo bar
}struct Obj {
key: String,
value: String,
}
fn main() {
let obj = Obj { key: "foo".to_string(), value: "bar".to_string() };
// pattern destructuring thật sự, tên trường phải khớp
let Obj { key, value } = obj;
println!("{key} {value}"); // foo bar
}struct Obj {
let key: String
let value: String
}
let obj = Obj(key: "foo", value: "bar")
// Swift không destructure struct theo tên trường trực tiếp,
// nhưng destructure tuple thì có
let (key, value) = (obj.key, obj.value)
print(key, value) // foo barrecord Obj(String key, String value) {}
void main() {
Obj obj = new Obj("foo", "bar");
// record pattern (Java 21+): destructure ngay trong instanceof
if (obj instanceof Obj(String key, String value)) {
IO.println(key + " " + value); // foo bar
}
}Tham khảo: github.com/miguelmota/golang-for-nodejs-developers#destructuring