package main
import "fmt"
type Order struct {
ID string
Amount int
Validated bool
Paid bool
}
func fetchOrder(orderID string) Result[Order, string] {
if orderID == "" {
return Err[Order]("order id is empty")
}
if orderID == "missing" {
return Err[Order]("order not found")
}
return Order{
ID: orderID,
Amount: 125,
Validated: false,
Paid: false,
}
}
func validateOrder(order Order) Result[Order, string] {
if order.Amount <= 0 {
return Err[Order]("invalid amount")
}
order.Validated = true
return order
}
func processPayment(order Order) Result[Order, string] {
if !order.Validated {
return Err[Order]("order must be validated before payment")
}
if order.ID == "declined" {
return Err[Order]("payment was declined")
}
order.Paid = true
return order
}
func processOrder(orderID string) Result[Order, string] {
order := fetchOrder(orderID)?
validated := validateOrder(order)?
payment := processPayment(validated)?
return payment
}
func main() {
ids := []string{"A-100", "", "missing", "declined"}
for _, id := range ids {
fmt.Printf("processing %q\n", id)
match processOrder(id) {
Ok(order) => fmt.Printf("success: id=%s amount=%d validated=%t paid=%t\n\n", order.ID, order.Amount, order.Validated, order.Paid),
Err(err) => fmt.Printf("error: %s\n\n", err),
}
}
}
The following Dingo code (click to view)
Should be equivalent to the following Go code
Benchmarks (click to open)
The results are somewhat disappointing:
Please correct me if I'm wrong, but the transpiler fails to produce an efficient Go equivalent and instead seems to alloc due to heap escaping of
dgo.Resultmembers: