在Go語言中,減少冗余代碼可以通過以下幾種方法實(shí)現(xiàn):
i
作為循環(huán)變量,而不是index
或iterator
。for i := 0; i < len(arr); i++ {
// 處理數(shù)組元素
}
strings.Join
而不是手動拼接字符串。package main
import (
"fmt"
"strings"
)
func main() {
strs := []string{"hello", "world"}
result := strings.Join(strs, " ")
fmt.Println(result)
}
type Predicate func(int) bool
func filter(numbers []int, predicate Predicate) []int {
var result []int
for _, num := range numbers {
if predicate(num) {
result = append(result, num)
}
}
return result
}
func main() {
numbers := []int{1, 2, 3, 4, 5}
evenNumbers := filter(numbers, func(num int) bool {
return num%2 == 0
})
fmt.Println(evenNumbers)
}
type Rectangle struct {
width, height float64
}
func (r Rectangle) Area() float64 {
return r.width * r.height
}
type Circle struct {
radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.radius * c.radius
}
func main() {
rect := Rectangle{width: 3, height: 4}
circle := Circle{radius: 5}
fmt.Println("Rectangle area:", rect.Area())
fmt.Println("Circle area:", circle.Area())
}
type Shape interface {
Area() float64
}
type Rectangle struct {
width, height float64
}
func (r Rectangle) Area() float64 {
return r.width * r.height
}
type Circle struct {
radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.radius * c.radius
}
func main() {
shapes := []Shape{Rectangle{width: 3, height: 4}, Circle{radius: 5}}
for _, shape := range shapes {
fmt.Println("Area:", shape.Area())
}
}
通過遵循這些方法,你可以在Go語言中有效地減少冗余代碼,提高代碼的可讀性、可維護(hù)性和可擴(kuò)展性。