Method chaining in multiple lines

602 views
Skip to first unread message

Denis P

unread,
Nov 24, 2022, 2:45:54 PM11/24/22
to golang-nuts
Hi guys,

I am struggling with making my code work in a way that multiple methods called in multiline approach. Does any gopher has an answer is there any solution to this:
```
type MyStuff struct { }

func CreateMyStuff() MyStuff {}

func (s MyStuff) DoJobOne() MyStuff {}

func (s MyStuff) DoJobTwo() MyStuff {}

...

result := CreateMyStuff()
    . DoJobOne() // Error: expected statement, found '.'
    . DoJobTwo()

```

I have an error " expected statement, found '.' ".
Is there any workaround?

Harris, Andrew

unread,
Nov 24, 2022, 2:50:04 PM11/24/22
to Denis P, golang-nuts
Period should be at the end of lines

Call().
Chain().
Done()


From: golan...@googlegroups.com <golan...@googlegroups.com> on behalf of Denis P <denis....@gmail.com>
Sent: Thursday, November 24, 2022 11:45:54 AM
To: golang-nuts <golan...@googlegroups.com>
Subject: [go-nuts] Method chaining in multiple lines
 
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/182bae0c-de3f-417e-82bb-07ca3d26e71an%40googlegroups.com.

Dan Kortschak

unread,
Nov 24, 2022, 2:51:55 PM11/24/22
to golan...@googlegroups.com
Fluent APIs are not very common in Go, but if you want to do this, you
will need to have the dot at the end of the line.

```
result := CreateMyStuff().
DoJobOne().
DoJobTwo()
``

This comes from the language's semicolon insertion rules. See
https://go.dev/ref/spec#Semicolons


Reply all
Reply to author
Forward
0 new messages