8

Interfaces 101 : Interface Type Assertion Ep. 6

 1 year ago
source link: https://www.ardanlabs.com/blog/2023/02/interfaces-101-interface-type-assertions.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Interfaces 101 : Interface Type Assertion Ep. 6

Author image

Ardan Labs

March 7, 2023
interfaces-06.jpg?v=1

Introduction

In episode 5, Miki wrote a function that counted the number of lines in a file with interfaces. The first thing his function did was to open a file with Go’s os.Open function. Miki chose this method because the variable returned by said function implements the io.Reader interface which is crucial for the next step. The remaining parts of this function consisted of a primitive type alias that satisfied the io.Writer interface and tracked the number of lines by increasing the Write method’s receiver value. To put the process in motion, Miki will invoke function io.Copy to trigger his type alias’ Write method and in essence, count the number of lines in the file.

In this video, Miki will write a versatile logging library with Go interfaces.The first prototype he proposes consists of a type with an io.Writer interface field to handle writing data for the logger. Upon completing the first design, Miki realizes his type is missing a Sync function, which will enable developers to move data into stable storage while logging. To meet this requirement, Miki will create a new interface type with a Sync function. Watch and learn how you can use type assertions to write simple, yet effective, code.

Things you will learn in this video

  • How to properly perform a type assertion on an interface.
  • How to move data from memory to stable storage.
  • Tips on designing an interface in Go.

Video


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK