Could not Convert MaybeString to String

Hi,

I’m coming from a Java tech stack and I’m brand new in the Go language. What I’m trying to do is use a sipParser library (GitHub - StefanKopieczek/gossip: SIP stack in Golang) to parse SipUri.
E.x: sip:bob@192.168.6.236:5060 So I wanna pick bob. I’m using
ParseSipUri method to parse it as below:

uri, err := parser.ParseSipUri(fromNumber)
fmt.Println("Parsed From Number:", uri.User) 

The above prints bob successfully but I need to convert uri.User(which is MaybeString type which is an interface) to string. I tried many different approaches but none of them worked. Can you help me to find a way to convert this?

Library’s SipUri structure below:

type SipUri struct {
	// True if and only if the URI is a SIPS URI.
	IsEncrypted bool

	// The user part of the URI: the 'joe' in sip:joe@bloggs.com
	// This is a pointer, so that URIs without a user part can have 'nil'.
	User MaybeString
...
...
...
}
type MaybeString interface {
	implementsMaybeString()
}

Hi @eaglesinblack,

Welcome to Go!

I am confused about the interfaces and its purpose. I took a quick and naïve attempt to implement a Go-ish version but I am not sure if it matches your situation.

Playground link

package main

import (
	"fmt"
	"log"
)

// This is a struct so that we can define a String() method.
type MaybeString struct {
	Name *string
}

// Implement the "Stringer" interface. The String() method is supposed
// to return a string representation of its type.
// Here, if Name is nil, String() returns an empty string, else the Name as a string.
func (ms *MaybeString) String() string {
	if ms == nil {
		return ""
	}
	return *(ms.Name)
}

type SipUri struct {
	IsEncrypted bool
	User        MaybeString
}

func ParseSipUri(n int) (SipUri, error) {
	return SipUri{false, MaybeString{Name: nil}}, nil
}

func main() {
	uri, err := ParseSipUri(23)
	if err != nil {
		log.Fatalf("Error parsing SIP URI")
	}
	fmt.Println("Parsed From Number:", uri.User)  // uri.User has a String() method. Println() is happy.
}

The idea:

  • MaybeString implements the Stringer interface. This interface allows any custom type to generate a string representation of itself. The fmt.PrintX() functions recognize the String() method.
  • Method string takes care of the possible nilness of the string and returns an empty string if Name is nil.

Sometimes looking at the tests can tell you how a type should be used. I found this strMaybeStr function in the tests and the way MaybeString is used there is like this:

func strMaybeStr(s base.MaybeString) string {
	switch s := s.(type) {
	case base.NoString:
		return "<none>"
	case base.String:
		return s.String()
	default:
		return "nil"
	}
}

So it looks like a MaybeString can be nil, or contains NoString or String.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.