教授 AI 现代围棋:用反重力解决“卡在过去”问题
发布: (2025年12月17日 GMT+8 17:40)
4 min read
原文: Dev.to
Source: Dev.to
问题:过时的默认值
LeetCode – 1. Two Sum
func TwoSum(nums []int, target int) []int {
seen := make(map[int]int)
for i, num := range nums {
comp := target - num
if idx, ok := seen[comp]; ok {
return []int{idx, i}
}
seen[num] = i
}
return nil
}
在提示代理 write benchmark for TwoSum function 时,通常会得到如下基准测试代码:
func BenchmarkTwoSum(b *testing.B) {
// Create a larger input for benchmarking
nums := make([]int, 1000)
for i := 0; i < 1000; i++ { // Old‑style loop
nums[i] = i
}
target := 1997
b.ResetTimer()
for i := 0; i < b.N; i++ { // Old‑style benchmark loop
TwoSum(nums, target)
}
}
问题
- 使用了传统的
for i := 0; i < 1000; i++循环,而不是现代的for i := range 1000。 - 手动使用
b.N,而不是 Go 1.24 引入的更新的b.Loop()方法。
解决方案:代理规则
在 Antigravity 中,Rule 是一个 Markdown 文件,用于定义代理的约束、偏好和风格指南。
(有关设置细节,请参阅文档。)
1. 现代化基准测试 (benchmark.md)
// benchmark.md
The `b.Loop` method is now the preferred way to write benchmarks in Go 1.24+.
func BenchmarkExample(b *testing.B) {
// ... setup ...
for b.Loop() {
// ... code to measure ...
}
// ... cleanup ...
}
Always use b.Loop() instead of b.N in benchmarks.
2. 现代化循环 (loops.md)
// loops.md
Each iteration creates a new instance of the variable. There is no need to declare `v := v` inside the loop for closure safety.
for _, v := range data {
go func() {
// safe to use v here directly
}()
}
// Integer ranges are now supported.
for i := range 10 {
fmt.Println(10 - i)
}
结果
添加规则文件并点击 Reload Rules 后,代理会遵循新的约定。再次提示:
write benchmark for TwoSum function
会产生如下计划:
[NEW] search_test.go
* Create `search_test.go`.
* Implement `BenchmarkTwoSum`.
* Use `b.Loop()` structure.
* Construct a large slice of integers and a target that tests worst/average cases.
更新后的基准测试
func BenchmarkTwoSum(b *testing.B) {
nums := make([]int, 1000)
for i := range 1000 {
nums[i] = i
}
target := 1997
for b.Loop() {
TwoSum(nums, target)
}
}
现在代码遵循了最新的 Go 规范,整体更为简洁。
更进一步:强制执行风格指南
规则还可以强制更广泛的风格指南。例如,你可以导入整个 Uber Go Style Guide 或任何自定义约定。
示例:强制错误包装 (errors.md)
// errors.md
Do not simply `return err`. Always wrap errors using `github.com/cockroachdb/errors` to provide stack traces and context. Use `Wrap(error, string)` or `Wrapf(error, string, ...interface{})`.
func getUser(id int) error {
if err := someDatabaseCall(id); err != nil {
// Wrap the original error with added context
return errors.Wrapf(err, "some database call id %d", id)
}
return nil
}
通过定义此类规则,你可以防止 LLM 回退到过时的模式,并确保生成的代码符合团队的工具和风格。规则弥合了 LLM 知识与实际代码需求之间的差距。