草庐IT

inheritance - 具有混合结构类型的 Go 映射和 slice

coder 2024-07-07 原文

我正在尝试通过创建一个能够创建投影的简单事件存储来学习如何使用 Go。我被困在如何使用包含混合类型结构的 slice 和映射上。这样做的要点是,我希望开发人员根据需要在各个字段中创建尽可能多的实现 IEntity 和 IEvent 的结构。

我来自 JavaScript/Node.js 背景,具有一些 C/C++/Java 的基本知识,我可能在这里寻找类/继承模式并需要一些帮助来了解如何在 Go 中获得相同的功能.

package main

import (
    "sync"
    "time"

    uuid "github.com/satori/go.uuid"
)

// IEntity describes an entity, a struct that is the sum of all events resolved in a chronological order
type IEntity interface {
}

// IProjection describes the interface for a projection struct
type IProjection interface {
    Lock()
    Unlock()
    Get(id uuid.UUID) IEntity
    Set(id uuid.UUID, entity IEntity)
    GetLastEventTime() time.Time
    Append(event IEvent)
}

// IEvent describes the interface for a event, any event added to the system needs to implement this interface
type IEvent interface {
    Resolve(projection IProjection)
}

// EventVault is the base struct that keeps all the events and allows for projections to be created
type EventVault struct {
    sync.Mutex
    events []IEvent
}

// Append adds a IEvent to the projection and runs that events IEvent.Resolve method
func (vault *EventVault) Append(event IEvent) {
    vault.Lock()
    defer vault.Unlock()
    vault.events = append(vault.events, event)
}

// Project creates a projection with entities from all events up until the choosen end time
func (vault *EventVault) Project(endTime time.Time, projection IProjection) IProjection {
    lastEventTime := projection.GetLastEventTime()
    for index := range vault.events {
        event := vault.events[index]
        if event.Time.After(lastEventTime) && event.Time.Before(endTime) {
            projection.Append(event)
        }
    }
    return projection
}

// Projection caculates and stores a projection of the events appended to it with the Append method
type Projection struct {
    sync.Mutex
    events   []IEvent
    entities map[uuid.UUID]IEntity
}

// Get returns an IEntity struct from an id (for use in the IEvent.Resolve method)
func (projection *Projection) Get(id uuid.UUID) IEntity {
    return projection.entities[id]
}

// Set add a IEntity to the projection (for use in the IEvent.Resolve method)
func (projection *Projection) Set(id uuid.UUID, entity IEntity) {
    projection.entities[id] = entity
}

// GetLastEventTime returns the time for the event that was added last
func (projection *Projection) GetLastEventTime() time.Time {
    event := projection.events[len(projection.events)-1]

    if event == nil {
        return time.Unix(0, 0)
    }

    return event.Time
}

// Append adds a IEvent to the projection and runs that events IEvent.Resolve method
func (projection *Projection) Append(event IEvent) {
    projection.Lock()
    projection.events = append(projection.events, event)
    event.Resolve(projection)
    projection.Unlock()
}

// ------------------ Below is usage of above system ------------------

// PlayerEntity is a sample entity that can be used for testing
type PlayerEntity struct {
    ID        uuid.UUID
    Name      string
    Birthday  time.Time
    UpdatedAt time.Time
}

// AddPlayerEvent is a sample event that can be used for testing
type AddPlayerEvent struct {
    ID   uuid.UUID
    Time time.Time
    Name string
}

// Resolve will create a new PlayerEntity and add that to the projection
func (event *AddPlayerEvent) Resolve(projection IProjection) {
    player := PlayerEntity{ID: uuid.NewV4(), Name: event.Name, UpdatedAt: event.Time}
    projection.Set(player.ID, &player)
}

// SetBirthdayPlayerEvent is a sample event that can be used for testing
type SetBirthdayPlayerEvent struct {
    ID       uuid.UUID
    Time     time.Time
    Birthday time.Time
}

// Resolve will change the name on a PlayerEntity
func (event *SetBirthdayPlayerEvent) Resolve(projection IProjection) {
    player := *projection.Get(event.ID)
    player.Birthday = event.Birthday
    player.UpdatedAt = event.Time
}

func main() {
    vault := EventVault{}
    event1 := AddPlayerEvent{ID: uuid.NewV4(), Time: time.Now(), Name: "Lisa"}
    vault.Append(&event1)
    birthday, _ := time.Parse("2006-01-02", "2017-03-04")
    event2 := SetBirthdayPlayerEvent{ID: event1.ID, Time: time.Now(), Birthday: birthday}
    vault.Append(&event2)
}

我得到的错误是

./main.go:47: event.Time undefined (type IEvent has no field or method Time)
./main.go:79: event.Time undefined (type IEvent has no field or method Time)
./main.go:122: invalid indirect of projection.Get(event.ID) (type IEntity)

结构类型可能丢失了,所以我需要另一种存储它们的方法,以便将它们放入映射和 slice 中,但是如何呢?

最佳答案

在 golang 中,当你声明一个像

这样的接口(interface)时
type IEntity interface {
}

您可以定义无需类型转换即可使用此接口(interface)完成的所有操作。所以在这里你没有为这个接口(interface)定义任何功能。如果你想要功能而不是你必须给它一个方法,比如

type IEntity interface {
    Time() time.Time
}

任何想要与该接口(interface)一起使用的类型都必须实现这些功能,即

func (a AddPlayerEvent) Time() time.Time {
    return a.Time 
} 

See the docs

然后你可以使用这些方法中的任何一个

func (projection *Projection) Append(event IEvent) {
    ...
    event.Time()
    ...
}

还有2条笔记

  • 遍历 map 时,您可以使用 k, v := range my_map
  • *projection.Get(event.ID) 尝试引用非指针类型

关于inheritance - 具有混合结构类型的 Go 映射和 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42924518/

有关inheritance - 具有混合结构类型的 Go 映射和 slice的更多相关文章

  1. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  2. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  3. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  4. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  5. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  6. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  7. ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等) - 2

    我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s

  8. ruby-on-rails - 在 Rails 开发环境中为 .ogv 文件设置 Mime 类型 - 2

    我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain

  9. ruby - 是否有用于序列化和反序列化各种格式的对象层次结构的模式? - 2

    给定一个复杂的对象层次结构,幸运的是它不包含循环引用,我如何实现支持各种格式的序列化?我不是来讨论实际实现的。相反,我正在寻找可能会派上用场的设计模式提示。更准确地说:我正在使用Ruby,我想解析XML和JSON数据以构建复杂的对象层次结构。此外,应该可以将该层次结构序列化为JSON、XML和可能的HTML。我可以为此使用Builder模式吗?在任何提到的情况下,我都有某种结构化数据-无论是在内存中还是文本中-我想用它来构建其他东西。我认为将序列化逻辑与实际业务逻辑分开会很好,这样我以后就可以轻松支持多种XML格式。 最佳答案 我最

  10. ruby-on-rails - Rails 3.1 中具有相同形式的多个模型? - 2

    我正在使用Rails3.1并在一个论坛上工作。我有一个名为Topic的模型,每个模型都有许多Post。当用户创建新主题时,他们也应该创建第一个Post。但是,我不确定如何以相同的形式执行此操作。这是我的代码:classTopic:destroyaccepts_nested_attributes_for:postsvalidates_presence_of:titleendclassPost...但这似乎不起作用。有什么想法吗?谢谢! 最佳答案 @Pablo的回答似乎有你需要的一切。但更具体地说...首先改变你View中的这一行对此#

随机推荐