Golang中的类与方法设计实践

Golang中的类与方法设计实践 我是Go框架的新手 虽然我一直在学习Go教程,但在实际应用时,我感到很困惑。在我编写的代码中,我有一些疑问。

以下是Python代码

table1 = 
{
  ‘q1’: [3]
  ‘q2’:[8,2]
  “x”:[0xAAA]
}

class checkIDS(object): 

    t1 = 0xaa
    t2 = 0xae

   def classmethodA(a, val):
     try:

     except :

   def classmethodB(a, name):
      try:

      except :

  bv = {
	     “T1”:        0x01,
	     “T2”:        0x03,
       }


class modA(checkIDS)
     def __init__(self,zz):

     bv.update({“T1”:0x03})

上面的Python代码被翻译成Go格式,如下所示

    type table1 struct 
        {
          q1  [3] byte
          q2 [8][2]byte
          x [0xAAA]byte
        }

    type object struct {
         a int
         b int
    }

如何在Go中重新定义以下几行?

class checkIDS(object) 及其下面的方法?

我尽力将其定义为

func (self *A)

但无法继续。如何在Go中将类定义为结构体类型?


更多关于Golang中的类与方法设计实践的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

你的 Python 代码缺少适当的空格,能否请你编辑一下你的帖子,将其放入代码块中?

除此之外,Go 语言中没有类的概念。

只有结构体,并且可以选择性地为其定义方法。

type s struct{}

func (s s) f() {
  fmt.Println("I'm here")
}

更重要的是,Go 语言中没有继承的概念。

更多关于Golang中的类与方法设计实践的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go中实现类似Python的类结构,可以通过结构体和方法接收器来完成。以下是完整的Go实现示例:

package main

import (
	"fmt"
)

// 对应 table1
type Table1 struct {
	Q1 [3]byte
	Q2 [8][2]byte
	X  [0xAAA]byte
}

// 对应 checkIDS 类
type CheckIDS struct {
	T1 uint8
	T2 uint8
	BV map[string]uint8
}

// 类方法A - 对应 classmethodA
func (c *CheckIDS) ClassMethodA(val interface{}) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("panic recovered: %v", r)
		}
	}()
	
	// 方法实现
	// 例如:处理val参数
	_ = val
	return nil
}

// 类方法B - 对应 classmethodB
func (c *CheckIDS) ClassMethodB(name string) (result interface{}, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("panic recovered: %v", r)
		}
	}()
	
	// 方法实现
	// 例如:根据name查找
	return name, nil
}

// 构造函数
func NewCheckIDS() *CheckIDS {
	return &CheckIDS{
		T1: 0xAA,
		T2: 0xAE,
		BV: map[string]uint8{
			"T1": 0x01,
			"T2": 0x03,
		},
	}
}

// 对应 modA 继承 checkIDS
type ModA struct {
	CheckIDS
	ZZ int
}

// ModA 构造函数
func NewModA(zz int) *ModA {
	modA := &ModA{
		CheckIDS: *NewCheckIDS(),
		ZZ:       zz,
	}
	// 更新 BV
	modA.BV["T1"] = 0x03
	return modA
}

func main() {
	// 使用示例
	table := Table1{
		Q1: [3]byte{1, 2, 3},
		Q2: [8][2]byte{{1, 2}, {3, 4}},
	}
	fmt.Printf("Table1: %+v\n", table)

	// 创建 CheckIDS 实例
	check := NewCheckIDS()
	fmt.Printf("CheckIDS T1: 0x%X\n", check.T1)
	fmt.Printf("CheckIDS BV: %v\n", check.BV)

	// 调用方法
	err := check.ClassMethodA("test")
	if err != nil {
		fmt.Printf("Error: %v\n", err)
	}

	result, err := check.ClassMethodB("query")
	if err != nil {
		fmt.Printf("Error: %v\n", err)
	} else {
		fmt.Printf("Result: %v\n", result)
	}

	// 创建 ModA 实例
	modA := NewModA(100)
	fmt.Printf("ModA T1: 0x%X\n", modA.T1)
	fmt.Printf("ModA BV[T1]: 0x%X\n", modA.BV["T1"])
	fmt.Printf("ModA ZZ: %d\n", modA.ZZ)
}

关键点说明:

  1. 结构体定义:使用type StructName struct定义类
  2. 方法定义:使用func (receiver *StructName) MethodName()语法
  3. 继承模拟:通过嵌入结构体实现组合
  4. 构造函数:使用NewStructName()模式
  5. 错误处理:使用Go的error返回机制替代try-catch
  6. 映射类型:使用map[string]uint8对应Python字典

运行输出:

Table1: {Q1:[1 2 3] Q2:[[1 2] [3 4] [0 0] [0 0] [0 0] [0 0] [0 0] [0 0]] X:[0 0 ...]}
CheckIDS T1: 0xAA
CheckIDS BV: map[T1:1 T2:3]
Result: query
ModA T1: 0xAA
ModA BV[T1]: 0x3
ModA ZZ: 100
回到顶部