Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Element.Create #141

Open
3052 opened this issue Nov 16, 2024 · 6 comments
Open

Element.Create #141

3052 opened this issue Nov 16, 2024 · 6 comments

Comments

@3052
Copy link

3052 commented Nov 16, 2024

Element should have a Create method or similar, to allow for more natural creation of nested values

doc := NewDocument()
doc.Create("People", func(e *Element) {
   e.Create("Person", func(e *Element) {
      e.CreateAttr("name", "Jon")
   })
   e.Create("Person", func(e *Element) {
      e.CreateAttr("name", "Sally")
   })
})
@3052 3052 changed the title Element.CreateElementFunc Element.Create Nov 17, 2024
@3052
Copy link
Author

3052 commented Nov 17, 2024

implementation

package etree

func (e *Element) Create(tag string, f func(*Element)) {
   f(e.CreateElement(tag))
}

@3052
Copy link
Author

3052 commented Nov 17, 2024

in case this is not accepted, here is a wrapper:

package etree

import "github.com/beevik/etree"

type Document struct {
   *etree.Document
}

func NewDocument() *Document {
   var d Document
   d.Document = etree.NewDocument()
   return &d
}

func (d Document) Element() *Element {
   return &Element{&d.Document.Element}
}

type Element struct {
   *etree.Element
}

func (e *Element) Create(tag string, f func(*Element)) {
   f(&Element{
      e.Element.CreateElement(tag),
   })
}

@beevik
Copy link
Owner

beevik commented Jan 17, 2025

While I understand the motivation for this feature, I'm not sure I agree that the package demands a new API for creating elements and attributes. Your approach is essentially syntactic sugar for the existing API, which doesn't directly support a "nested" style of element creation. I think I prefer keeping the API surfaces concise so there is less ambiguity in how to do things.

@beevik
Copy link
Owner

beevik commented Jan 17, 2025

After giving it more thought (and seeing the precedent you described in x/crypto) I've decided to go ahead and add your proposed API. It's currently visible in this branch.

@3052
Copy link
Author

3052 commented Jan 18, 2025

note this style is also documented here

https://wikipedia.org/wiki/Continuation-passing_style

@3052 3052 mentioned this issue Jan 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants