package reflux // Get 按路径取值并直接转成目标类型 T,不产生中间的 R 包装对象。 // // name := reflux.Get[string](r, "Address", "City") // age := reflux.Get[int](r, "Age") // // 语义与 r.Get(path...).Xxx() 严格等价,是可以放心替换的写法: // - 路径不存在 / 未导出字段 / 下标越界 -> 返回 T 的零值 // - 类型转换失败 -> panic,错误信息与访问器方法一致 // // 与链式写法的区别只在开销: 链式的 r.Get(...).String() 每次都要在堆上新建一个 // R 包装对象,而这里直接把结果写进调用方的变量,常见标量类型下**零分配**。 // // 覆盖 string / int / int64 / bool / float64 五种类型;其余类型走通用路径, // 行为与 r.Get(path...).Any().(T) 一致。 // // 注意: T 只出现在返回值里,无法类型推导,必须显式写出 Get[string](...)。 func Get[T any](r R, path ...string) T { var out T // 用 any(&out) 而不是 any(out) 做类型分发: 前者装箱的是指针, // 指针本身就是接口的数据字段,不需要额外堆分配;后者会把值拷进堆。 switch p := any(&out).(type) { case *string: if g, ok := r.(*rfx); ok { *p = g.getString(path...) } else { *p = r.Get(detachPath(path)...).String() } case *int: if g, ok := r.(*rfx); ok { *p = g.getInt(path...) } else { *p = r.Get(detachPath(path)...).Int() } case *int64: if g, ok := r.(*rfx); ok { *p = g.getInt64(path...) } else { *p = r.Get(detachPath(path)...).Int64() } case *bool: if g, ok := r.(*rfx); ok { *p = g.getBool(path...) } else { *p = r.Get(detachPath(path)...).Bool() } case *float64: if g, ok := r.(*rfx); ok { *p = g.getFloat64(path...) } else { *p = r.Get(detachPath(path)...).Float64() } default: // 非标量类型: 退回通用路径 if x, ok := r.Get(detachPath(path)...).Any().(T); ok { out = x } } return out } // detachPath 复制一份路径切片。 // // 这一步看着多余,实则必要: 下面那些 r.Get(...) 是**接口动态调用**,逃逸分析 // 看不穿,于是判定 path 整体逃逸 —— 哪怕运行时走的是上面的快分支。 // 在慢分支里复制一份切断数据流,快分支的可变参数才能留在栈上。 // 少了这一步,Get[string] 会从 0 分配退化成 1 次 48 字节分配。 func detachPath(p []string) []string { q := make([]string, len(p)) copy(q, p) return q }