登录
首页 >  Golang >  Go问答

在Golang中如何将正则表达式嵌入到proto结构?

来源:stackoverflow

时间:2024-03-11 18:33:25 354浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《在Golang中如何将正则表达式嵌入到proto结构?》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我有一个类似树的结构,它有字符串正则表达式,我希望 go 编译的 *regexp.regexp 也成为它的一部分,以便在树上运行算法。当我编组并将其传递到另一台机器时,我可能只是从字符串中再次重新编译它。正确的方法是什么,如何强制 protobuf 将指针存储在结构中,理想情况下它不会封送? (我看到的唯一方法是创建 uint64 字段并将其值转换为 *regexp 或从 *regexp 转换)

伪代码(因为所需的功能似乎不在该语言中):

// struct generated by protoc
type ProtoMessage struct {
    Data string
    Source string
    Regexp uint64 // should not be marshalled, should be forcefully omitted from payload when doing proto.Marshal, ideally it should be *regexp.Regexp
    Left   *ProtoMessage
    Right  *ProtoMessage
}

func main() {
    // sender computer doSend():
    mSrc := &ProtoMessage{Data:"its meee!!!", Source: "hello.+world"}
    payload, _ := proto.Marshal(m)

    //receiver computer: onRecv()
    mDst := new(ProtoMessage)
    proto.Unmarshal(payload, mDst)
    r, _ := regexp.Compile(mDst.Source)
    mDst.Regexp = uint64(unsafe.Pointer(r)) // not working btw

    TreeMatch = func(tree* ProtoMessage, line string) string {
        if *regexp.Regexp(t.Regexp).Match(line) { // not working line
            return t.Data
        }
        if tree.Left == nil {
            return ""
        }
        return TreeMatch(tree.Left, line)
    }

    assert( TreeMatch(mDst, "hello, world") == "its meee!!!") // panic if condition is false
}

使用 json marshal,我可以将一个指向 regexp 的指针并提供一个标签 json:"-" 以便不将该字段包含到编组结构中,并且使用其编组/解组系统的重要功能来保持高效(例如使用相同的结构在 in 上运行算法,并避免解组后的数据复制)。我怎样才能用 protobuf 做同样的事情?


正确答案


您无法将指针存储在 protobuf 中,因为接收者可能是另一台计算机。即使可以,当您尝试取消引用指针时,您也会感到恐慌。最简单的事情就是传递 regexp 字符串,然后在目的地再次编译:

package main

import (
   "fmt"
   "google.golang.org/protobuf/proto"
   "google.golang.org/protobuf/types/known/structpb"
)

func main() {
   v := structpb.newstringvalue("hello.+world")
   b, err := proto.marshal(v)
   if err != nil {
      panic(err)
   }
   fmt.printf("%q\n", b) // "\x1a\fhello.+world"
}

注意:你也无法使用 gob 来解决这个问题:

package main

import (
   "bytes"
   "encoding/gob"
   "regexp"
)

func main() {
   re := regexp.MustCompile("hello.+world")
   buf := new(bytes.Buffer)
   if err := gob.NewEncoder(buf).Encode(re); err != nil {
      panic(err) // type regexp.Regexp has no exported fields
   }
}

今天关于《在Golang中如何将正则表达式嵌入到proto结构?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>