Golang Program to Create an Interface Named Writer that Defines a Write Method


In this Golang article we will learn to create an interface named writer that defines a write method write method for file type as well as writer interface and filet type.

Syntax

data := []byte("Hello, World!")
  • It is used to declare a byte slice in go language.

  • data : it is a variable declaration for a var named data.

  • []byte: the type of variable “data” as a byte slice.

  • it is used to convert the string literal into byte slice.

Example 1

In this example, we are going to interface named writers that include a write() method. The code given below demonstrates writing data into a file by calling write method on file object.

package main

import "fmt"

type Writer interface {
   Write(p []byte) (n int, err error)
}

type File struct {
}

func (f *File) Write(p []byte) (n int, err error) {
   return len(p), nil
}

func main() {
   file := &File{}

   data := []byte("Hello, World!")

   bytesWritten, err := file.Write(data)
   if err != nil {
      fmt.Println("Error:", err)
      return
   }

   fmt.Println("Bytes written:", bytesWritten)
}

Output

Bytes Written : 13

Example 2

In this method instead of creating a struct we can use the built in os.file() type that satisfies the writer interface. The below code demonstrates the use of interface and struct to write data into a file.

package main

import "fmt"

type Writer interface {
   Write(p []byte) (n int, err error)
}

type File struct {
}

func (f *File) Write(p []byte) (n int, err error) {
   return len(p), nil
}

func main() {
   file := &File{}

   data := []byte("Hello, World!")

   bytesWritten, err := writeToFile(file, data)
   if err != nil {
      fmt.Println("Error:", err)
      return
   }

   fmt.Println("Bytes written:", bytesWritten)
}

func writeToFile(writer Writer, data []byte) (int, error) {
   return writer.Write(data)
}  

Output

Bytes Written : 13

Conclusion

In this article we have discussed how we can create an interface named writer that defines a write method. We have explored different examples of writing data to a file using the Writer interface and the File type emphasized the advantages of interfaces and their role in fostering code reusability and abstraction.

Updated on: 13-Jul-2023

60 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements