LEARN VOID / DATA & BEHAVIOR

Inheritance & dispatch

Extend a managed type and choose virtual behavior explicitly.

Complete program for the synchronous entry adapter. The result below is the returned integer.

inheritance.voidDownload source
struct shipping:
    rate: i32 = 2

virtual func (service shipping) cost(weight: i32) -> i32:
    return service.rate * weight

struct express_shipping extends shipping:
    surcharge: i32 = 5

override func (service express_shipping) cost(weight: i32) -> i32:
    return super.cost(weight) + service.surcharge

func entry(weight: i32) -> i32:
    var express = express_shipping()
    var service: shipping = express
    return service.cost(weight)
Input 5Expected result 15

Extend a managed type

The shipping base type stores a rate of two. Express shipping extends it with a surcharge of five. The derived object retains its identity when assigned to a base-type view.

Choose virtual dispatch explicitly

The base cost method is virtual. The override first calls super.cost(weight), then adds the surcharge. Ordinary methods do not become virtual automatically.

Call through the base view

Although service is typed as shipping, it refers to the express object, so its override runs. Weight 5 gives 2 × 5 + 5 = 15. The view does not slice or duplicate the object.