MED Send Message

Create a SendMessage method for the User struct.

It should take a message string and messageLength int as inputs.

If the messageLength is within the user's message character limit, return the original message and true (indicating the message can be sent), otherwise, return an empty string and false.

package main


func (u User) SendMessage(message string, messageLength int) (string,bool){
	
	inLimit := messageLength <= u.MessageCharLimit

	if inLimit == true{
		return message, inLimit
	}else{
		return "",inLimit
	}
}

// don't touch below this line

type User struct {
	Name string
	Membership
}

type Membership struct {
	Type             string
	MessageCharLimit int
}

func newUser(name string, membershipType string) User {
	membership := Membership{Type: membershipType}
	if membershipType == "premium" {
		membership.MessageCharLimit = 1000
	} else {
		membership.Type = "standard"
		membership.MessageCharLimit = 100
	}
	return User{Name: name, Membership: membership}
}

Test

1

1. Structs

  • User represents a person with a name and a membership.

  • Membership is embedded, meaning User can access its fields directly (like u.MessageCharLimit).

2

2. Membership limits

  • A standard user can send messages up to 100 characters.

  • A premium user can send up to 1000 characters.

3

3. Creating a new user

Example:

4

4. SendMessage method

  • (u User) means this function belongs to the User type.

  • (string, bool) are the two return values — the message and whether it’s valid.

  • It compares the message’s length (messageLength) to u.MessageCharLimit.

5

5. Logic

  • inLimit becomes true if message length is small enough.

  • If true, send the message.

  • If false, block it and return an empty string.


Example Usage

Key Takeaways

  • func (u User) → defines a method attached to the User struct.

  • Return types (string, bool) → Go supports returning multiple values.

  • Embedded structs → allow direct field access like u.MessageCharLimit.

  • Logical check → use <= to compare message length with limit.