Golang fmt.Stringer类(方法)实例源码

下面列出了Golang fmt.Stringer 类(方法)源码代码实例,从而了解它的用法。

作者:coreo    项目:coreos-metadat   
func String(s fmt.Stringer) string {
	if reflect.ValueOf(s).IsNil() {
		return ""
	}

	return s.String()
}

作者:jde    项目:oinker-g   
func TestGraphSupportsDownCasting(t *testing.T) {
	RegisterTestingT(t)

	graph := inject.NewGraph()

	var (
		d fmt.Stringer
	)

	graph.Define(&d, inject.NewProvider(NewD))
	graph.ResolveAll()

	Expect(d).To(Equal(NewD()))
	Expect(d.String()).To(Equal("&ImplD{}"))

	expectedString := `&graph\{
  definitions: \[
    &definition\{
      ptr: \*fmt\.Stringer=0x.*,
      provider: &provider\{
        constructor: func\(\) \*test\.ImplD,
        argPtrs: \[\]
      \},
      value: <\*test\.ImplD Value>
    \}
  \]
\}`
	Expect(graph.String()).To(MatchRegexp(expectedString))
}

作者:dz0n    项目:sto   
func TestInterfaces(t *testing.T) {
	db, err := bolt.Open("my4.db", 0600, nil)
	if err != nil {
		t.Error(err.Error())
	}
	defer os.Remove("my4.db")
	defer db.Close()

	s := NewStore(db, []byte("interface"))

	var j fmt.Stringer = &MyType{"First", "Last"}
	s.Put([]byte("test"), &j)

	err = s.ForEach(func(str fmt.Stringer) {
		if str.String() != "First Last" {
			t.Errorf("unexpected string %s", str)
		}
	})
	if err != nil {
		t.Error(err.Error())
	}

	var i fmt.Stringer
	err = s.Get([]byte("test"), &i)
	if err != nil {
		t.Error(err.Error())
	} else {
		if i.String() != "First Last" {
			t.Errorf("unexpected string %s", i)
		}
	}
}

作者:pombredann    项目:pbt   
// Insert adds a new item to the hash map or, if the key already exists,
// replaces the current item with the new one.
func (pm *ParMap) Insert(item fmt.Stringer) {
	key := item.String()
	shard := pm.getShard(key)
	shard.mutex.Lock()
	shard.index[key] = item
	shard.mutex.Unlock()
}

作者:malsto    项目:terraform-provider-bos   
func testStringMatch(t *testing.T, s fmt.Stringer, expected string) {
	actual := strings.TrimSpace(s.String())
	expected = strings.TrimSpace(expected)
	if actual != expected {
		t.Fatalf("Actual\n\n%s\n\nExpected:\n\n%s", actual, expected)
	}
}

作者:taskcluste    项目:taskcluster-base-g   
func assert(t *testing.T, o fmt.Stringer, s string) {
	if o.String() != s {
		t.Log("Expected object to be resolved differently as a String:")
		t.Logf("Object: %#v", o)
		t.Logf("Expected: %q", s)
		t.Fatalf("Got: %q", o.String())
	}
}

作者:kiljacke    项目:ar   
func (v *ASTStringer) AddWithFallback(color string, what fmt.Stringer, fallback string) *ASTStringer {
	if !isNil(what) {
		v.AddStringColored(color, what.String())
	} else {
		v.AddStringColored(color, fallback)
	}
	return v
}

作者:ColB    项目:amazon-ecs-ini   
func (cLogger *commonLogger) processLogMsg(level LogLevel, message fmt.Stringer, context LogContextInterface) {
	defer func() {
		if err := recover(); err != nil {
			reportInternalError(fmt.Errorf("recovered from panic during message processing: %s", err))
		}
	}()
	if cLogger.config.IsAllowed(level, context) {
		cLogger.config.RootDispatcher.Dispatch(message.String(), level, context, reportInternalError)
	}
}

作者:jackspiro    项目:chi   
// Lookup finds the first node in the current scope by name.
func (s *Scope) Lookup(token fmt.Stringer) (ssa.Node, error) {
	name := token.String()
	if s.Empty() {
		return nil, fmt.Errorf("can't find a node '%s' in an empty scope stack", name)
	}
	for _, symtab := range s.stack.list {
		if symtab.contains(name) {
			return symtab.get(name)
		}
	}
	return nil, fmt.Errorf("'%s' not yet declared", name)
}

作者:qban    项目:dow   
func safeString(str fmt.Stringer) (s string, ok bool) {
	defer func() {
		if panicVal := recover(); panicVal != nil {
			if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() {
				s, ok = "null", false
			} else {
				panic(panicVal)
			}
		}
	}()
	s, ok = str.String(), true
	return
}

作者:gledge    项目:ap   
func safeString(str fmt.Stringer) (s string) {
	defer func() {
		if panicVal := recover(); panicVal != nil {
			if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() {
				s = "NULL"
			} else {
				panic(panicVal)
			}
		}
	}()
	s = str.String()
	return
}

作者:jackspiro    项目:chi   
// Global sets a node and its name in the global scope.
func (s *Scope) Global(token fmt.Stringer, n ssa.Node) error {
	name := token.String()
	symtab, err := s.stack.bottom()
	if err != nil {
		return err
	}
	if symtab.contains(name) {
		return fmt.Errorf("'%s' already declared globally", name)
	}
	err = symtab.set(name, n)
	if err != nil {
		return err
	}
	return nil
}

作者:stoiclab    项目:blockchain   
func (cLogger *commonLogger) processLogMsg(
	level LogLevel,
	message fmt.Stringer,
	context logContextInterface) {

	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()

	if cLogger.config.IsAllowed(level, context) {
		cLogger.config.RootDispatcher.Dispatch(message.String(), level, context, reportInternalError)
	}
}

作者:jackspiro    项目:chi   
// Add adds a name to the topmost scope in the scope stack.
func (s *Scope) Add(token fmt.Stringer, n ssa.Node) error {
	name := token.String()
	if s.Contains(name) {
		return fmt.Errorf("'%s' already declared", name)
	}
	symtab, err := s.stack.peek()
	if err != nil {
		return err
	}
	err = symtab.set(name, n)
	if err != nil {
		return err
	}
	return nil
}

作者:farshidt    项目:go-nx   
func TestNXTStringer(t *testing.T) {
	name, devicePath := "testingbot", "/dev/tty-foobar"
	var n fmt.Stringer
	n = NewNXT(name, devicePath)

	if n == nil {
		t.Errorf("Calling NewNXT should not result in a nil NXT instance.")
		return
	}

	expected, actual := fmt.Sprintf("NXT \"%s\": %s", name, devicePath), n.String()
	if actual != expected {
		t.Errorf("Expected NXT.String to return \"%s\", but got \"%s\" instead", expected, actual)
	}
}

作者:jlertl    项目:webb   
func (w *Web) pathDealer(re *regexp.Regexp, str fmt.Stringer) {
	names := re.SubexpNames()
	matches := re.FindStringSubmatch(str.String())

	for key, name := range names {
		if name != "" {
			w.Param.Set(name, matches[key])
		}
	}

	switch str.(type) {
	case pathStr:
		w.pri.curpath += matches[0]
		w.pri.path = w.pri.path[re.FindStringIndex(w.pri.path)[1]:]
	}
}

作者:jackspiro    项目:chi   
// Trust takes a name token and node that has not yet been defined and "trusts"
// that it will be defined later according to the node type values that were
// implied by the parser.
func (t *TBV) Trust(token fmt.Stringer, node ssa.Node) {
	name := token.String()
	if _, ok := t.table[name]; ok {
		// p.enter()("'" + name + "' is already being trusted.")
	} else {
		t.table[name] = node
	}
}

作者:reconques    项目:orgalor   
// SendSync sends SYNC message to the writer, tagging it as sent from node,
// described by given source and adding optional description for the given
// SYNC phase taken by extraction it from the original SYNC message, sent
// by node.
func (protocol *syncProtocol) SendSync(
	source fmt.Stringer,
	sync string,
) error {
	data := strings.TrimSpace(
		strings.TrimPrefix(sync, protocol.prefix+" "+syncProtocolSync),
	)

	_, err := io.WriteString(
		protocol.output,
		syncProtocolSync+" "+source.String()+" "+data+"\n",
	)

	if err != nil {
		return protocolSuspendEOF(err)
	}

	return nil
}

作者:Manoue    项目:go-viduch   
//AddValue ajoute dans la BD
func (dbManager *DbManager) AddValue(bucketName string, key string, object fmt.Stringer) error {

	err := dbManager.db.Update(func(tx *bolt.Tx) error {
		bucket, err := tx.CreateBucketIfNotExists([]byte(bucketName))
		if err != nil {
			return err
		}

		encoded := object.String()

		return bucket.Put([]byte(key), []byte(encoded))
	})

	if err == nil {
		logger.Print("Ajout de " + key + " dans la bd")
	} else {
		logger.Error("Erreur lors de l'ajout dans la bd", err)
	}

	return nil
}

作者:jackspiro    项目:chi   
// Verify verifies that the provided token and node match with a corresponding
// pair that were trusted previously.
func (t *TBV) Verify(tok fmt.Stringer, node ssa.Node) (bool, error) {

	name := tok.String()

	// check if the node is present in the TBV table
	if trustNode, ok := t.table[name]; ok {

		if trustNode.Type() != node.Type() {
			return true, errors.New("mismatch types")
		}

		switch trustNode.Type().Token() {
		case token.FUNC:

			trustFuncType := trustNode.Type().(*types.Func)
			funcType := node.Type().(*types.Func)

			if trustFuncType.Value() != nil {
				if trustFuncType.Value() != funcType.Value() {
					return false, errors.New("The function '" + name + "' must return either a type " + trustFuncType.Value().String() + " or " + funcType.Value().String() + ". Not both.")
				}
			}
			if trustFuncType.Arity() != funcType.Arity() {
				return false, errors.New("Number of arguments do not match.")
			}
			trustParam := trustFuncType.Param()
			param := funcType.Param()
			for param != nil {
				if param != trustParam {
					return false, errors.New("Parameter types are off.")
				}
				param = param.Next()
				trustParam = trustParam.Next()
			}
			return true, nil
		}
	}
	return false, nil
}


问题


面经


文章

微信
公众号

扫码关注公众号