我正在学习GO,我正在尝试实现一些不太琐碎的东西,一个持久的平衡树,我想知道我写的代码是否是惯用的。
以下是不完整的代码:
package main
import (
"fmt"
"errors"
)
type Node struct{
value int
left * Node
right * Node
}
func TraverseTree(root Node) {
if root.value != 0 {
TraverseTree(*root.left)
fmt.Println(root.value)
TraverseTree(*root.right)}
return
}
func MakeNode(value int) (Node) {
node := Node{value: value,
right: &Node{},
left: &Node{}}
return node
}
func AddNode(root Node, value int) (newNode Node, error error){
alreadyPresentError := errors.New("Element already present")
if root.value == 0 {
fmt.Println("Creating new Node of value: ", value)
newNode = MakeNode(value)
error = nil
} else if root.value == value {
newNode = root
error = alreadyPresentError
}else if value > root.value{ //going right
fmt.Println("Going Right")
nodeLeft, err := AddNode(*root.right, value)
if err != nil {
newNode = root
err = alreadyPresentError
}else{
newNode = Node{value: root.value,
left: root.left,
right: &nodeLeft}
error = nil}
}else if value < root.value{ //going left
fmt.Println("Going left")
nodeRight, err := AddNode(*root.left, value)
if err != nil {
newNode = root
err = alreadyPresentError
}else{
newNode = Node{value: root.value,
left: &nodeRight,
right: root.right}
error = nil}}
return
}
什么不能说服我是如何管理错误,但可能还有其他错误。
答案 0 :(得分:1)
有几件事需要处理:
go fmt
switch
代替if-else链其余的更多是品味问题。你可以通过不使用命名返回值来使代码更清晰,但这是我的意见。以下是我的建议:
// Moved it up here to reuse a single instance of the error
var alreadyPresentError = errors.New("Element already present")
func AddNode(root Node, value int) (Node, error) {
switch {
case root.value == 0:
fmt.Println("Creating new Node of value: ", value)
return MakeNode(value), nil
case root.value == value:
return root, alreadyPresentError
case value > root.value:
//going right
fmt.Println("Going Right")
nodeLeft, err := AddNode(*root.right, value)
if err != nil {
return root, alreadyPresentError
}
return Node{value: root.value,
left: root.left,
right: &nodeLeft}, nil
case value < root.value: //going left
fmt.Println("Going left")
nodeRight, err := AddNode(*root.left, value)
if err != nil {
return root, alreadyPresentError
}
return Node{value: root.value,
left: &nodeRight,
right: root.right}, nil
}
// Dummy return. If you don't like dummies, delete the case root.value == value case
return root, alreadyPresentError
}